1. Atomic operation:
CAS--compareandswap (), which refers to multiple threads entering a critical region, allows multiple threads to compete freely on a critical area, and finally ensures that one thread wins, and other threads that are not competing can try again. All threads on the final critical region are able to complete thread security, which is also called a lock-free way, and in the previous synchronized, other threads are not allowed to enter the critical area to work. The lock-free way only guarantees thread security, unlike the previously-spoken synchronization mechanism, so the thread cannot be dispatched in an orderly manner. CAS programming features: No locks are required to maintain thread security (the most classic count++) for shared resources (protected data). Multiple threads Execute counters.
Under the direct method (without any operating conditions):
View Code
Output: As seen from the output results, some thread output values are the same: the main reason count++ is not an atomic type of operation, count++ this directive contains three parts: Read---Modify---write, In the course of this thread competition, when some threads are reading shared count, there are just a few other threads here that are dropping the count, resulting in both threads having +1 count at the same time, and finally writing memory at the same time, so that we feel the same value as the output.
pool-1-thread-3 thread--3pool-1-thread-1 thread--4pool-1-thread-4 thread--4pool-1-thread-2 thread--3 Pool-1-thread-4 thread--7pool-1-thread-1 thread--6pool-1-thread-3 thread--5pool-1-thread-1 thread--10 Pool-1-thread-1 thread--12pool-1-thread-1 thread--13pool-1-thread-4 thread--9pool-1-thread-4 thread--14 Pool-1-thread-4 thread--15pool-1-thread-2 thread--8pool-1-thread-2 thread--16pool-1-thread-2 thread--17 Pool-1-thread-2 thread--18pool-1-thread-3 thread--11pool-1-thread-3 thread--19pool-1-thread-3 thread--20
The first way to join a lock is to solve this way: public synchronized void Run ()
1 pool-1-thread-3 thread--1 2 pool-1-thread-3 thread--2 3 pool-1-thread-3 thread--3 4 pool-1-thread-3 thread--4 5 pool-1-thread-3 thread--5 6 Pool -1-thread-1 thread--6 7 pool-1-thread-1 thread--7 8 pool-1-thread-1 thread--8 9 pool-1-thread-1 thread--910 pool-1-thread-1 thread--1011 Pool-1-thread-2 thread--1112 pool-1-thread-2 thread--1213 pool-1-thread-2 thread--1314 pool-1-thread-2 thread--1415 Pool-1-thread-2 thread--1516 pool-1-thread-4 thread--1617 pool-1-thread-4 thread--1718 pool-1-thread-4 thread--1819 pool-1-thread-4 thread--1920 pool-1-thread-4 thread--20
The second approach uses a lock-free mechanism: The CAS Operation directive: The atomic class has the mechanism of using this kind of CAs, the use of this non-blocking algorithm
Principle: CAs consists of 3 parameters: Memory location V, old value A, new value B, when the value of position v equals a, CAS updates a with the new value B by atomic operation, and the CAS operation mechanism is compared with compareandset (A, B) method. This approach is used in the nature of atomic operations: constant attempts in the loop, when the return value is successful
Also here this simple Gaga operation, using the atomic class in the JDK
Package Javaconcurrentdemo; 2 import java.util.concurrent.atomic.AtomicInteger; 6 7 public class Atomicintegerdemo Implements runnable{8 static Atomicinteger count=new Atomicinteger (); 9 public void Count.incrementandget ( ); System.out.println (Thread.CurrentThread (). GetName () + "thread--" + }14 public static void main (string[] args) {//TODO auto-generated method stub16 Countdemo t=new countdemo (); Executorservice exce= Executors.newfixedthreadpool (4); + for (int i=0;i<4;i++ }24}
Non-blocking algorithm: A thread should not affect the operation of other programs when it fails or hangs:: Atomic class is only a non-blocking algorithm for the use, but simple Gaga can be implemented with the atomic class, Implement thread security (data security) in a complex algorithm using its own compiled non-blocking algorithm (with one of the underlying atomic machine directives (CAS)) instead of locks
On this basis, the use of compareandset instead of the front used to Count.incrementandget (), to obtain a sequence of non-repetition
1 pool-1-thread-1 thread--1 2 pool-1-thread-3 thread--2 3 pool-1-thread-3 thread--4 4 pool-1-thread-1 thread--6 5 pool-1-thread-2 thread--5 6 Pool -1-thread-1 thread--8 7 pool-1-thread-4 thread--3 8 pool-1-thread-3 thread--7 9 pool-1-thread-4 thread--1110 pool-1-thread-1 thread--1011 Pool-1-thread-1 thread--1412 pool-1-thread-2 thread--913 pool-1-thread-2 thread--1514 pool-1-thread-4 thread--1315 pool-1-thread-3 thread--1216 pool-1-thread-4 thread--1717 pool-1-thread-4 thread--1918 pool-1-thread-3 thread--1819 Pool-1-thread-2 thread--1620 pool-1-thread-2 thread--20
1Package Javaconcurrentdemo; 2 3Import Java.util.concurrent.ExecutorService; 4Import java.util.concurrent.Executors; 5Import Java.util.concurrent.atomic.AtomicInteger; 6 7 public class Counterdemo {8 public static class Cascount implements runnable{9 static Atomicinteger count=new Atomic Integer (0 ), ten public void run (), {13///with Increament method, using Copareandset instead of count.incrementandget (); + for (int i=0;i<5;i++ )- {(true ) + {count.compareandset (Count.get (), Count.get () +1 ) {System.out.println (Thread.CurrentThread (). GetName () + "thread--" +count.get ()); Break }23 }24 }27 }28 }30 public static void Main (string[] A RGS) {//TODO auto-generated method Stub32 executorservice Exce=executors.newfixedthreadpool (4 ); i<4;i++ ) {exce.submit (new cascount ()); }37 }38. span>
The non-blocking algorithm is programmed with CAS nature, and the high concurrency is indeed higher than the lock's performance, but if a thread repeatedly accesses a zone.
An exclusive lock is a pessimistic lock, synchronized is an exclusive lock that assumes a worst case scenario and only executes if the other thread is not causing interference, causing all other threads that need to be locked to hang, waiting for the thread that holds the lock to release the lock. Another more effective lock is the optimistic lock. The so-called optimistic lock is that each time without locking but assume that there is no conflict to complete an operation, if the conflict failed to retry, until successful
This optimistic lock is called no lock, with the lock to the critical area is barrier-free, through the CAS algorithm (with multiple threads trying to use CAS simultaneously update the same variable, only one of the threads can update the value of the variable, while the other threads fail, the failed thread is not suspended, but is told that the competition failed, and can try again). CAS operation of the instructions of the CPU, only one step atomic operation, must be tested thread-safe.
Problems with 4.CAS operation:
Although CAS operations can efficiently resolve atomic operations: three questions:
1. Long cycle time overhead . Spin CAs can cause very large execution overhead for CPUs if they are unsuccessful for a long time. If the JVM can support the pause instruction provided by the processor then the efficiency will be improved, the pause command has two functions, first it can delay the pipelining instruction (de-pipeline), so that the CPU does not consume excessive execution resources, the delay depends on the specific implementation of the version, On some processors, the delay time is zero. Second, it avoids the CPU pipelining being emptied (CPU pipeline flush) when exiting the loop due to memory order collisions (violation), which improves CPU execution efficiency.
2. only one atomic operation of a shared variable can be guaranteed . When performing operations on a shared variable, we can use the method of circular CAs to guarantee atomic operations, but for multiple shared variables, the cyclic CAS cannot guarantee the atomicity of the operation, it is possible to use locks at this time, or there is a trickery way to combine multiple shared variables into a single shared variable to operate. For example, there are two shared variable i=2,j=a, merge ij=2a, and then use CAs to manipulate IJ. Starting with Java1.5 The JDK provides the Atomicreference class to guarantee atomicity between reference objects, and you can put multiple variables in an object for CAS operations. If you want to maintain the atomicity of multiple variables, use the Atomicreference class to encapsulate multiple variables, and then perform a CAS operation on the object.
Introduce the Jdk.atomic class:
Atomicinteger ()----primarily treats integers
Atomicreference ()-----Atomic manipulation of an object
Atomicintegerarray[]----to an array of integers
3. The third issue of the ABA problem----only the Compareandset () method is not able to solve the ABA problem, adding an additional method atomicstampedreference () that can record the number of times the Compareandset () changes to the variable A.
ABA PROBLEM: Thread 1 wants to change the value of variable A to B, before this occurs, thread 2 has changed the value of the variable from a to B in the presence of a thread changed from B to a, (the value of variable A is modified several times) at this time thread 1 in the go to the variable CAs operation to find the value of a variable or a, So CAs succeeds (other line Cheng), although the values are the same but at this point the scene is actually different from the original. Because the Compareandset operation has occurred several times in this process:
The following example about automatic phone charging, business hall free for mobile phone recharge 20 yuan A time: This process is similar to ABA operation
1 packageAtomictest; 2 3 ImportJava.util.concurrent.atomic.AtomicStampedReference; 4 5 public classAtomicstampedreferencedemo {6 static atomicstampedreference<integer> moneny=new atomicstampedreference< Integer> (19,0); 7 public static voidMain (string[] args) {8//TODO auto-generated Method stub 9//three top-up programs are monitored here, a consumer program for (int i= 0;i<3;i++)//execute three top-up consumption monitoring {final int timestamp=moneny.getstamp ();//The first parameter indicates the first balance, the second parameter indicates the number of recharge Times newThread () 13{14//each process has its own run method, public voidRun () 16{+ while (true) 18{Integer m=Moneny.getreference (); if (m<20) 21{if (Moneny.compareandset (m,m+20,timestamp,timestamp+1)) 23{System.out.println ("Insufficient balance, automatic recharge of 20 yuan, existing balance" +Moneny.getreference ());; 26}27 Else28{System.out.println ("to help you recharge one time, can not be sent");; 31}32 }34 else35 {$ break ; PNs }38 }39 }40 }.start (); $ }42//user mode new Thread () {i=0;i<100;i++ public void Run () {$ (int ) (True )- {m= moneny.getreference (), int timestamp= moneny.getstamp (), and if (m> ) System.out.println ("Money is greater than 10 yuan" + m); Moneny.compareandset (m,m-10,timestamp,timestamp+ 1 ); {System.out.println ("Consumption is greater than 10 yuan" + moneny.getreference ()); "$ break ;" }59 60 }61 else62 {//why *. GetReference will be modified in CAs System.out.println ("Not Enough balance" ); , + }66 }67 }68 }69 }.start (); }71 "
Java Multithreading Analysis (vii)----CAS operations and blocking