Volatile and synchronized in Java Multi-threading

Source: Internet
Author: User

 PackageCom.chzhao; Public classVolatiletestextendsThread {Private Static intCount = 0;  Public voidRun () {count++; }     Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000];  for(inti = 0; i < threads.length; i++) {Threads[i]=Newvolatiletest (); }         for(inti = 0; i < threads.length; i++) {Threads[i].start (); }        Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (count); }}

The code above, expecting the output is 10000, then, because count++ is not thread-safe, so the output is often less than 10000.

To solve this problem, the volatile keyword was added.

 PackageCom.chzhao; Public classVolatiletestextendsThread {Private volatile Static intCount = 0;  Public voidRun () {count++; }     Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000];  for(inti = 0; i < threads.length; i++) {Threads[i]=Newvolatiletest (); }         for(inti = 0; i < threads.length; i++) {Threads[i].start (); }        Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (count); }}

After modification, a value other than 10000 is often output.

Modified to synchronized form, the code is as follows:

 PackageCom.chzhao; Public classSynchronizedtestextendsThread {Private Static intCount = 0;  Public voidrun () {synchronized(lockclass.lock) {count++; }    }     Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000];  for(inti = 0; i < threads.length; i++) {Threads[i]=Newsynchronizedtest (); }         for(inti = 0; i < threads.length; i++) {Threads[i].start (); }        Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (count); }}
 Package Com.chzhao;  Public class Lockclass {    publicstaticbytenewbyte[0];}

After this modification, the output is 10000.

Does this mean that the keyword "volatile" is completely useless? Only synchronized can guarantee thread safety?

In the Java theory and Practice: Correct use of Volatile variables, it is mentioned that:

The Java™ language contains two intrinsic synchronization mechanisms: synchronous blocks (or methods) and volatile variables. Both of these mechanisms are proposed to achieve the security of code threads. Where volatile variables are less synchronous (but sometimes simpler and less expensive), and their use is more error-prone. Volatile variables in the Java language can be thought of as "light", and synchronized synchronized volatile variables require less coding and run-time overhead than blocks, but only part of the functionality that they can implement synchronized .

That is to say, in some cases, volitile is more convenient than synchronized, and of course, synchronization is even more nearly.

See "Java Theory and Practice: using Volatile variables correctly"

Reference:
Http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

Volatile and synchronized in Java Multi-threading

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.