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

Source: Internet
Author: User
Tags cas

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 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 classCasdemo {2     Private Final intThread_num = 1000;3     Private Final intMax_value = 20000000;4     PrivateAtomicinteger CasI =NewAtomicinteger (0);5     Private intSynci = 0;6     PrivateString Path = "/users/pingping/datacenter/books/linux/linux common command in detail. txt";7 8      Public voidCasadd ()throwsinterruptedexception {9         LongBegin =System.currenttimemillis ();Tenthread[] Threads =NewThread[thread_num]; One          for(inti = 0; i < Thread_num; i++) { AThreads[i] =NewThread (NewRunnable () { -                  Public voidrun () { -                      while(Casi.get () <max_value) { the casi.getandincrement (); -                     } -                 } -             }); + Threads[i].start (); -         } +          for(intj = 0; J < Thread_num; J + +) { A Threads[j].join (); at         } -System.out.println ("CAS Costs Time:" + (System.currenttimemillis ()-begin)); -     } -  -      Public voidSyncadd ()throwsinterruptedexception { -         LongBegin =System.currenttimemillis (); inthread[] Threads =NewThread[thread_num]; -          for(inti = 0; i < Thread_num; i++) { toThreads[i] =NewThread (NewRunnable () { +                  Public voidrun () { -                      while(Synci <max_value) { the                         synchronized("Synci") { *++Synci; $                         }Panax Notoginseng                     } -                 } the             }); + Threads[i].start (); A         } the          for(intj = 0; J < Thread_num; J + +) + Threads[j].join (); -SYSTEM.OUT.PRINTLN ("Sync costs Time:" + (System.currenttimemillis ()-begin)); $     } $}

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 () <                                            }

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 classCasdemo {2     Private Final intThread_num = 1000;3     Private Final intMax_value = 1000;4     PrivateAtomicinteger CasI =NewAtomicinteger (0);5     Private intSynci = 0;6     PrivateString Path = "/users/pingping/datacenter/books/linux/linux common command in detail. txt";7 8      Public voidCASADD2 ()throwsinterruptedexception {9         LongBegin =System.currenttimemillis ();Tenthread[] Threads =NewThread[thread_num]; One          for(inti = 0; i < Thread_num; i++) { AThreads[i] =NewThread (NewRunnable () { -                  Public voidrun () { -                      while(Casi.get () <max_value) { the casi.getandincrement (); -                         Try(InputStream in =NewFileInputStream (NewFile (path)) { -                                  while(In.read ()! =-1); -}Catch(IOException e) { + e.printstacktrace (); -                         } +                     } A                 } at             }); - Threads[i].start (); -         } -          for(intj = 0; J < Thread_num; J + +) - Threads[j].join (); -System.out.println ("CAS Random costs Time:" + (System.currenttimemillis ()-begin)); in     } -  to      Public voidSYNCADD2 ()throwsinterruptedexception { +         LongBegin =System.currenttimemillis (); -thread[] Threads =NewThread[thread_num]; the          for(inti = 0; i < Thread_num; i++) { *Threads[i] =NewThread (NewRunnable () { $                  Public voidrun () {Panax Notoginseng                      while(Synci <max_value) { -                         synchronized("Synci") { the++Synci; +                         } A                         Try(InputStream in =NewFileInputStream (NewFile (path)) { the                              while(In.read ()! =-1); +}Catch(IOException e) { - e.printstacktrace (); $                         } $                     } -                 } -             }); the Threads[i].start (); -         }Wuyi          for(intj = 0; J < Thread_num; J + +) the Threads[j].join (); -SYSTEM.OUT.PRINTLN ("Sync costs Time:" + (System.currenttimemillis ()-begin)); Wu     } -}

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.

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

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.