Lock is a pessimistic strategy, always feel that there will be problems, so careful to operate.
No lock is an optimistic strategy, always assume that there will be no problem, if there is a problem, then re-operation. Lock-free generally uses CAS as a policy.
Compare Exchange CAs:
The CAS algorithm consists of three parameters: the variable to be updated, the expected value, and the updated value. It is only when the value that needs to be updated equals the expected value that the other thread does not manipulate it so that the update value is equal to the update value.
In Java.util.concurrent.atomic, there are a number of unlocked types implemented:
Write a small example with Atomicinteger:
Public classDemoImplementsrunnable{StaticAtomicinteger ai=NewAtomicinteger (); Public Static voidMain (string[] args)throwsinterruptedexception {executorservice es=executors.newfixedthreadpool (10); for(inti=0;i<10;i++) {Es.submit (Newdemo ()); } thread.sleep (1000); SYSTEM.OUT.PRINTLN (AI); } Public voidrun () { for(inti=0;i<100;i++) {ai.incrementandget (); } }}
Without locking, the output of 1000,atomicxx is atomic, and the specific method can see the API itself.
Let's take a look at the Incrementandget () method:
Public Final int Incrementandget () { for (;;) { int current = get (); int Next = current + 1; if (Compareandset (current, next)) return next; } }
As described on the face of the CAS algorithm, keep trying until successful, enter Compareandset ():
Public Final boolean compareandset (intint update) { return Unsafe.compareandswapint (This, Valueoffset, expect, update); }
Call the unsafe class of compareandswapint, only need to know his approximate meaning of the line, through the field offset to find the location, through the expectation and the value to be updated to determine whether to update.
Java High concurrency Programming (10)--No lock