Atomicinteger can guarantee that the operation of an integral type is atomic. Like i++ This operation is not atomic operation, there is a race condition, so need to lock, but the performance of locking is not high, if only to add 1 to an integer. Let's look at his realization.
private volatile int value;
The Atomicinteger itself holds an integer variable, and all operations are based on that variable. The variable is modified by violate, which is guaranteed to be visible and visible in another blog
Java Concurrency Learning Note (vi)-Mutex and memory visibility.
Take a look at the operation of value plus 1
Public final int getandincrement () {for (;;) { int current = Get (); int next = current + 1; if (Compareandset (current, next)) return to current; } }
The code is nested within a for loop, and the key is in the Compareandset method. This method is managed to the Compareandswapint method of unsafe, which is supported by hardware and is atomic operation. This means that if value equals current, then value is set to Next, return true, or false to continue the next round. Why there is a value inconsistency, because in a race condition, when this thread assigns value value to current, other threads may modify the value of values, so that there is a case of inconsistency between the present and the value. Can be seen to compareandset similar optimistic lock, timely failure. In summary, the visibility of value is guaranteed by voilate, and atomic operations are guaranteed by Compareandset.
The other way, the operation is similar, all rely on compareandset to ensure
Java Concurrency Learning Note (ix)-Atomic class Atomicinteger