Objective
In Java and the contract has such a package, java.util.concurrent.atomic, the package is the Java part of the data type of atomic encapsulation, on the basis of the original data type, provides an atomic operation method, to ensure thread safety. Take Atomicinteger, for example, to see how it is implemented.
Public final int Incrementandget () {for (;;) { int current = Get (); int next = current + 1; if (Compareandset (current, next)) return next;} }
Public final int Decrementandget () {for (;;) { int current = Get (); int next = current-1; if (Compareandset (current, next)) return next;} }
Taking these two methods as an example, the Incrementandget method is equivalent to the atomicity of the ++i,decrementandget method equivalent to the atomicity of the-I (according to the first chapter and the second chapter we know that ++i or-I is not an atomic operation), Neither of these methods uses a blocking approach to ensure atomicity (such as synchronized), 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 perform atomic read and write operations 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 expected value. Then, when the two values are equal, the CPU replaces the values in memory with the new values. Otherwise, do not do the operation. Finally, the CPU returns the old value. This series of operations is atomic. Although seemingly complex, they are the root of the Java 5 concurrency mechanism, which is superior to the original locking mechanism. Simply put, the meaning of CAS is "What I think the original value should be, if it is, update the original value to a new value, otherwise do not modify, and tell me what the original value is." (this description is quoted from the Java Concurrency Programming practice)
Simply put, CAS has 3 operands, a memory value of V, an old expected value of a, and a new value to be modified B. if and only if both the expected value A and the memory value v are the same, the memory value V is modified to B, otherwise V is returned. This is an optimistic locking idea, it is believed that before it modifies, there is no other thread to modify it, and synchronized is a pessimistic lock, it is believed 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 for atomic operations.
Volatile variable
private volatile int value;
First, a volatile variable value is declared, and in the second chapter we know that volatile guarantees the memory visibility of the variable, which means that all worker threads can get a consistent value at the same time.
Public final int Get () { return value;}
Compare and Set
Setup to use Unsafe.compareandswapint for updatesprivate static final unsafe unsafe = Unsafe.getunsafe ();p rivate static The final long valueoffset;//note is static statically { try { valueoffset = Unsafe.objectfieldoffset ( AtomicInteger.class.getDeclaredField ("value"));//reflect the Value property, get 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, here using the unsafe class of JNI method implementation, using CAS directive, can guarantee that read-write is an atomic operation. Compareandswapint has 4 parameters, this-the current Atomicinteger object, the position of the Offset-value property in memory (which needs to be emphasized is not the value in memory position), expect-expected value, update- The new value, based on the CAS procedure above, updates the value in memory to the update value and returns True if the value in memory equals the expect value, otherwise false. Here we need to have a simple understanding of the unsafe, from the name, it is not safe, indeed, this class is used to perform low-level, unsafe operation of a collection of methods, the method in this class is mostly memory direct operation, so unsafe, but when we use reflection, and the contract, have been indirectly used in the unsafe.
Looping settings
Now look at the two methods mentioned in the opening, we take incrementandget to analyze the implementation process.
Public final int Incrementandget () {for (;;) {//This is better than while (true) int = get ();//Gets the current value int next = present + 1;//Set update value if (compareandset (current, NE XT)) return to Next;} }
Loop, gets the current value and sets the update value, calls Compareandset for the CAS operation, returns to the update if successful, or retries 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 the value (the idea is too), this is of course a small probability of time, the current Java seems to be unable to handle this situation.
Disadvantages
Although the use of CAs can achieve non-blocking atomic operation, but will produce ABA problems, about the ABA problem, the plan to take out a chapter to organize. (end) This article from: Gao | Coder, the original address: http://blog.csdn.net/ghsau/article/details/38471987, reprint please specify.