JDK achieve lock as there are two types: Synchronized and CAS
CAS is used, there are used directly, such AtomicInterger; indirect use, such as ReentrantLock
1, CAS introduced
CAS is a Compare and Swap (compare and swap) for short
CAS three operands: memory value V, the expected value of the old A, B values to be modified, if and only if the expected value V A and the memory values are equal, the memory value is modified B and returns true, false otherwise
2, Unfafe
Unsafe has a lower class in JDK sun.misc package, which methods are native methods that provide hardware-level operating principle
public final native boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5); public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5); public final native boolean compareAndSwapLong(Object var1, long var2, long var4, long var6);
These methods can be used directly within the JDK (our personal writing class can not call these methods directly), all the basic CAS operations are achieved through these compareAndSwap of Unsafe methods.
3, AtomicInteger source code analysis
Source structure is as follows
Number The class of AtomicInteger the extends the implements public the java.io.Serializable { // Create instance Unsave Private Final static Unsafe.getUnsafe the Unsafe the unsafe = (); // initial value, the use of volatile type, to ensure the visibility of the Private volatile int value; public of AtomicInteger (int the initialValue) { value = the initialValue; } public of AtomicInteger () { } }
4, AtomicInteger use
= New new AtomicInteger of AtomicInteger of AtomicInteger (); // sets the initial value atomicInteger.set (10); // I similar ++ int I = atomicInteger.incrementAndGet ()
5, incrementAndGet () method
Final int incrementAndGet public () { // call the method unsafe.getAndAddInt return unsafe.getAndAddInt (the this, valueOffset,. 1) +. 1; } // call unsafe.getAndAddInt method public final int getAndAddInt (Object var1, long var2, int var4) { int var5; do { // get the current new value, the value for the latest stop, and in the most current value + 1'd var5 = this.getIntVolatile (var1, var2); // this.compareAndSwapInt () method is native type the // If the method returns false, which is set in the case of failure, has been circulating until the setting is successful } the while (this.compareAndSwapInt (var1, var2, var5, var5 + var4)!); return var5; }