In the Java and the contract has such a package, java.util.concurrent.atomic, the package is the Java part of the data type of the atomic encapsulation, on the basis of the original data type, provides the atomic operation method, guaranteed the thread safety. Take Atomicinteger as an example and see how it is achieved.
[Java]View Plain copy print? Public final int Incrementandget () {for (;;) {int current = get (); int next = current + 1; if (Compareandset, next) return to next; } }
[Java]View Plain copy print? Public final int Decrementandget () {for (;;) {int current = get (); int next = current-1; if (Compareandset, next) return to next; } }
Take these two methods as an example, the Incrementandget method is equivalent to the atomic ++i,decrementandget method-------------------we know that ++i or I are not an atomic operation according to the first chapter and the second chapter, Neither of these methods uses a blocking approach to ensure atomicity (such as synchronized), so how do they guarantee atomicity, and the following leads to CAS. Compare and Swap
CAS refers to a special instruction that is widely supported by modern CPUs in the operation of shared data in memory. This instruction will do an atomic read and write operation on the shared data in memory. Briefly describe the operation of this instruction: first, the CPU compares the data that will be changed in memory with the desired value. Then, when the two values are equal, the CPU replaces the values in memory with the new value. Otherwise the operation will not be done. Finally, the CPU returns the old values. This series of operations is atomic. Although they may seem complex, they are the root of the Java 5 concurrency mechanism superior to the original lock mechanism. In short, the meaning of CAS is "I think what the original value should be, if it is, then update the original value to the new value, otherwise do not make changes, and tell me what the original value is." (This is a quote from Java Concurrency programming practice)
In simple terms, CAS has 3 operands, memory value V, old expected value A, new value B to modify.if and only if the expected value A and the memory value v are the same, the memory value V is modified to B, otherwise the V is returned。 This is an optimistic lock idea, it believes that before it changes, no other thread to modify it, and synchronized is a pessimistic lock, it believes that before it changes, there must be other threads to modify it, pessimistic lock efficiency is very low. Let's take a look at how Atomicinteger uses CAs to achieve atomic operations.volatile Variable [Java]View Plain copy print? private volatile int value; First we declare a volatile variable value, and in the second chapter we know that volatile guarantees the memory visibility of the variable, that is, a consistent value can be obtained at the same time in all worker threads.[Java]View Plain copy print? Public final int Get () {return value; }Compare and Set [Java] View Plain copy print? setup to use Unsafe.compareAndSwapInt for updates private Static final unsafe unsafe = unsafe.getunsafe (); private static final long valueoffset;// Note is static static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField ("value"));// Reflects the Value property, gets its position in memory } catch (EXCEPTION EX) { throw new error (ex); } } Public final boolean compareandset ( int expect, int update) { return unsafe.compareandswapint (this , valueoffset, expect, update); }   compare and set, which is implemented using the JNI method of the unsafe class, using CAS directives to ensure that read-change-write is an atomic operation. Compareandswapint has 4 parameters, this-the current Atomicinteger object, the position of the Offset-value attribute in memory (the place to emphasize is not the value in memory), expect-expected, update- The new value, based on the CAS procedure above, when the value value in memory is equal to the expect value, the value in memory is updated to the update value and returns True, or false. It is necessary for us to have a simple understanding of unsafe. From the name point of view, it is not safe, indeed, this class is used to perform low-level, unsafe operation of the collection of methods, the method in this class is mostly direct memory operation, so unsafe, but when we use reflection, and the contract, are indirectly used in the unsafe.Looping SettingsNow looking at the two methods mentioned in the opening paragraph, let's take a incrementandget to analyze the implementation process.[Java]View Plain copy print? Public final int Incrementandget () {for (;;) {//This is better than while (true) int current = GET ()//Gets the current value int next = present + 1;//Set update value if (compare Andset (current, next)] return to next; Within the loop, get the current value and set the update value, call Compareandset for CAS operations, and if successful, return to the update, or retry until successful. There may be a hidden danger, that is, the cycle time is too long, always in the current thread compareandset, there is another thread set value (the idea is too much), this is certainly a small probability of time, the current Java seemingly can not handle this situation.Disadvantage Although it is possible to use CAS for non-blocking atomic operations, there is an ABA problem, and the plan takes a chapter in order to organize the ABA issue. (end) Original address: http://blog.csdn.net/ghsau/article/details/38471987