I. CAS algorithm
The process of the Compare and Swap,cas algorithm is this: it contains 3 parameter CAs (v,e,n). V represents the variable to be updated, E represents the expected value, and n represents the new value. The value of V is set to n only if the V value equals the E value, and if the V and E values are different, the current thread does nothing if the other thread has already updated. Finally, the CAs returns the true value of the current v. CAS operations are carried out in an optimistic manner and always think that they can successfully complete the operation. When multiple threads use CAs to manipulate a variable at the same time, only one wins, and the update succeeds, and the rest fails. Failed threads are not suspended, they are only told to fail, and they are allowed to try again, and of course allow failed threads to abandon the operation. Based on this principle, CAS operations do not have locks on the fly, and other threads can be found to interfere with the current thread and handle it appropriately.
Two. Unsafe class (implements the key class without lock):
Unsafe provides pointers to C + + operations. Non-secure operations, such as setting values based on Offsets Park () low-level CAS operations non-public API, in different versions of the JDK, there may be a large difference
Main interface:
Gets the int value on the offset of the given object
public native int getInt (Object o, long offset);
Sets the int value on the offset of the given object
public native void Putint (Object o, long offset, int x);
Get the offset of a field in an object
Public native long Objectfieldoffset (Field f);
Sets the int value of the given object, using the volatile semantics
public native void Putintvolatile (Object o, long offset, int x);
Gets the int value of the given object object, using the volatile semantics
public native int Getintvolatile (Object o, long offset);
Same as Putintvolatile (), but it requires that the field being manipulated is a volatile type
public native void Putorderedint (Object o, long offset, int x);
Three. No lock class:
1.AtomicInteger:
Api:
Public final int get ()//Get current value
Public final void set (int newvalue)//Set Current value
Public final int Getandset (int newvalue)//Set new value and return old value
Public final Boolean compareandset (int expect, int u)//If the current value is expect, set to U
Public final int getandincrement ()//Current value plus 1, return old value
Public final int getanddecrement ()//current value minus 1, return old value
Public final int getandadd (int delta)//Current value increment delta, return old value
Public final int Incrementandget ()//Current value plus 1, return new value
Public final int Decrementandget ()//current value minus 1, return new value
Public final int addandget (int delta)//Current value increment delta, return new value
Preliminary study on concurrent---Atomic lock-free