The use of Atomicinteger in Java

Source: Internet
Author: User

Atomicinteger, named with Atomic, is obviously atomic in nature. This class is often thread-safe and is mostly used for high concurrency modification of data.
With regard to multithreading atomicity, it is also recalled that the visibility of
Atomic Nature
Atomicity has an indivisible character. Atomic operation, with atomic nature. For example i=0 belongs to atomic operations, again such as i++, which is actually i = i + 1, is divisible, belongs to non-atomic operation. Non-atomic operations are not thread-safe, and sychronized are often used to synchronize atomic operations in multiple threads. Atomicinteger, Atomiclong, etc. are atomic operations, under Java.util.concurrent.atomic
Visibility of
Visibility refers to the visibility between threads, and one thread can see the results of another thread's operations. Variables that are often modified with a volatile representation have visibility. Volatile does not guarantee its atomicity and is non-linear security.

The following code contrasts with the Atomicinteger atomicity

 Public classTestatomicinteger {Static  inti = 0; StaticAtomicinteger a=NewAtomicinteger (0); Static classMyThreadImplementsRunnable {synchronized Public voidrun () { for(intm = 0; M < 1000; m++) {a.getandincrement (); I++;    }        }    };  Public Static voidMain (string[] args)throwsException {MyThread m=NewMyThread (); Thread T1=NewThread (m); Thread T2=NewThread (m);          T1.start ();          T2.start ();          System.out.println (i);    System.out.println (A.get ()); }}

Add synchronized Output results
2000
2000
No synchronized output results
1986
2000
It turns out that Atomicinteger is thread-safe and atomic.

Below analysis under Atomicinteger source code:

//setup to use Unsafe.compareandswapint for updatesPrivate Static Finalunsafe unsafe =Unsafe.getunsafe ();Private Static Final LongValueoffset;Private volatile intvalue;Static {      Try{Valueoffset=Unsafe.objectfieldoffset (Atomicinteger.class. Getdeclaredfield ("value")); } Catch(Exception ex) {Throw NewError (ex);} }

The unsafe class provides hardware-level atomic operations that can allocate and free memory, locating the memory location of a field of an object. Source comments provide "compare and replace" when updating operations
Valueoffset is used to record memory address offsets
Value is modified by volatile, the current thread can get the most recent value when updating the operation

 Public Final intIncrementandget () { for (;;) {            intCurrent =get (); intNext = current + 1; if(Compareandset (current, next))returnNext; }    } Public Final BooleanCompareandset (intExpectintupdate) {        returnUnsafe.compareandswapint ( This, Valueoffset, expect, update); }

int current = get (); Here you can get the most recent value

Unsafe.compareandswapint (); Use the native method of unsafe to achieve efficient hardware-level CAs

The use of Atomicinteger in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.