Summary of Java concurrent Programming 2--use CAS with caution

Source: Internet
Author: User

I. CAs and synchronized application scenarios

1, for less resources competition, using synchronized synchronization lock for thread blocking and wake-up switching and user-state kernel state switching operation additional waste of CPU resources, and CAS based on hardware implementation, do not need to enter the kernel, do not need to switch threads, the operation spin probability is less, Therefore, higher performance can be achieved.

2, for the resource competition serious situation, CAS spin probability will be relatively large, thus wasting more CPU resources, efficiency is less than synchronized. Taking the Atomicinteger class in the Java.util.concurrent.atomic package as an example, its getandincrement () method is implemented as follows:

Public final int getandincrement () {for        (;;) {            int current = Get ();            int next = current + 1;            if (Compareandset (current, next))                return to current;        }}

If the Compareandset (current, Next) method executes successfully, it returns directly; if the thread is fiercely competitive, causing the compareandset (current, next) method to fail to execute successfully, the loop waits This significantly reduces efficiency until the time slices that the CPU allocates to the thread are exhausted.

Second, CAS errors in the use of the scene

 1 public class Casdemo {2 private final int thread_num = 3, private final int max_value = 20000000; 4 p Rivate Atomicinteger CasI = new Atomicinteger (0); 5 private int synci = 0; 6 private String Path = "/users/pingping/datacenter/books/linux/linux common commands in detail. txt"; 7 8 public void Casadd () throws Interruptedexception {9 Long begin = System.currenttimemillis (); hread[] Threads = new thread[thread_num];11 for (int i = 0; i < Thread_num; i++) {Threads[i] = n EW Thread (New Runnable () {public void Run () {(Casi.get () < Max_value) {             Casi.getandincrement (); 16}17}18}); 19 Threads[i].start ();}21 for (int j = 0; J < Thread_num; J + +) {threads[j].join (); 2 3}24 System.out.println ("CAS Costs Time:" + (System.currenttimemillis ()-begin)); 25    }26 public void Syncadd () throws interruptedexception {long begin = System.currenttimemillis (); 29 thread[] Threads = new thread[thread_num];30 for (int i = 0; i < Thread_num; i++) {Threads  [I] = new Thread (new Runnable () {public void run () {Synci < Max_value)                      {synchronized ("Synci") {++synci;36}37 }38}39}); Threads[i].start ();}42 for ( int j = 0; J < Thread_num; J + +) Threads[j].join (); System.out.println ("Sync costs Time:" + (System.currenttimemillis ()-Beg in)); 45}46}

Running on my dual-core CPU, the results are as follows:

It can be seen that in different threads, CAS computing consumes much more time than using the Synchronized method. The reason is that line 15th

                     while (Casi.get () < Max_value) {                         casi.getandincrement ();                     

Operation is a very little time-consuming operation, and after 15 lines are executed, they go into the loop immediately and continue execution, causing a serious thread conflict.

Iii. improved CAS usage scenarios

In order to solve these problems, it is only necessary to make each cycle execute longer, that is, the thread conflict can be greatly reduced. Modify the code as follows:

 1 public class Casdemo {2 private final int thread_num = 3 private final int max_value = 4 Priva Te atomicinteger CasI = new Atomicinteger (0); 5 private int synci = 0; 6 private String Path = "/users/pingping/datacenter/books/linux/linux common commands in detail. txt";         7 8 public void CasAdd2 () throws Interruptedexception {9 Long begin = System.currenttimemillis (); 10 thread[] Threads = new thread[thread_num];11 for (int i = 0; i < Thread_num; i++) {Threads[i] = New Thread (New Runnable () {public void Run () {(Casi.get () < Max_value) {casi.getandincrement (); try (inputstream in = new FileInputStream (NE  W File (Path)) {in.read () = 1); catch (IOException                     e) {e.printstacktrace (); 20}21}22}23}); Threads[i].start ();}26 for (int j = 0; J < THR Ead_num;  J + +) Threads[j].join (); System.out.println ("CAS Random costs Time:" + (System.currenttimemillis () (begin));}30 public void SyncAdd2 () throws interruptedexception {Long begin = System.currenttim             Emillis (); thread[] threads = new thread[thread_num];34 for (int i = 0; i < Thread_num; i++) {35 Threads[i] = new Thread (new Runnable () {$ public void run () {PNS while (Synci                         < Max_value) {synchronized ("Synci") {++synci;40                             }41 try (InputStream in = new FileInputStream (new File)) {42 while (In.read ()! =-1); catch (IOException e) {E.prin Tstacktrace (); 45}46}47}48}); Threads[i].start () ;}51 for (int j = 0; J < Thread_num; J + +) Threads[j].join (); System.out.prin TLN ("Sync costs Time:" + (System.currenttimemillis ()-Begin)); 54}55}

In the while loop, an operation that reads the contents of a file is added, which takes approximately 40ms of time to reduce thread collisions. The test results are as follows:

It can be seen that in the case of relatively small resource conflicts, the use of CAs mode and synchronized synchronization efficiency is similar. Why is CAS not getting higher performance compared to synchronized?

The JDK used for the test was 1.7, and the implementation of the lock introduced a number of optimizations, starting with jdk1.6, such as Lock coarsening (lock coarsening), lock cancellation (lock elimination), lightweight lock (lightweight Locking), Techniques such as biased locking (biased Locking), adaptive Spin (Adaptive Spinning) reduce the overhead of locking operations. The principle of spin-lock, which is similar to CAS spin, is even more optimized than CAS spin. For details, refer to the deep JVM lock mechanism 1-synchronized.

Portal: http://blog.csdn.net/chen77716/article/details/6618779

Iv. Summary

1, the use of CAS thread conflict is serious, will significantly reduce program performance; CAS is only suitable for situations where there is less thread conflict.

2, synchronized after jdk1.6, has improved the optimization. Synchronized the underlying implementation of the main rely on the Lock-free queue, the basic idea is the spin after blocking, competition after the switch to continue the competition lock, a little sacrifice of fairness, but achieved high throughput. With fewer thread conflicts, you can get similar performance to CAS, which is much higher than CAs in the case of a severely threaded conflict.

Http://www.cnblogs.com/everSeeker/p/5569414.html

Java Concurrency Programming summary 2--use CAS (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.