Java multi-thread volatile keyword

Source: Internet
Author: User

In Java thread concurrency processing, the primary role of keyword volatile is to make a variable visible across multiple threads. So what 's the use of volatile? Let's first look at a piece of code:

public class MyThread1 implements Runnable {private Boolean Istag = True;public Boolean Isistag () {return istag;} public void Setistag (Boolean istag) {this.istag = Istag;} public void print () {try {while (Istag) {System.out.println ("print () thread name is:" +thread.currentthread (). GetName ()); Thread.Sleep (1000);}} catch (Exception e) {}} @Overridepublic void Run () {print ();}}

public class MyThread {public static void main (string[] args) {MyThread1 m=new MyThread1 (); new Thread (M). Start (); SYSTEM.OUT.PRINTLN ("I want to stop looping---" +thread.currentthread (). GetName ()); M.setistag (false);}}

If this code is running, we can see that the thread stops properly. If the code is running on a 64bit JVM in-server server mode, a dead loop occurs. The solution is to usevolatile keyword. The role of the keyword volatile is to force the value of the variable to be taken from the public stack, rather than getting the value of the variable from the thread private data stack.

We will transform the code:

public class MyThread1 extends Thread {private volatile Boolean Istag = True;public Boolean Isistag () {return istag;} public void Setistag (Boolean istag) {this.istag = Istag;} @Overridepublic void Run () {System.out.println ("enter run () = ="), while (Istag) {System.out.println ("Thread name is:" + Thread.CurrentThread (). GetName ());} SYSTEM.OUT.PRINTLN ("thread is stopped = = =");}}


Using the volatile keyword increases the visibility of instance variables across multiple threads. But the most deadly disadvantage of the volatile keyword is that it does not support atomicity.


The keyword synchronized is compared with volatile:

    1. keyword volatile is a lightweight implementation of thread synchronization, so volatile performance is certainly better than synchronized, and volatile can only modify variables, and synchronized may modify the method, and code blocks. With the release of the new JDK version, synchronized keyword execution efficiency, the use of synchronized in development is more.
    2. multithreaded access Volatile does not clog, while synchronized may become clogged.
    3. volatile guarantees the visibility of the data, but does not guarantee atomicity, and synchronized can guarantee atomicity, or indirectly, because it synchronizes the private memory with the data in public memory.
    4. keyword volatile addresses the visibility of variables across multiple threads While the Synchronized keyword solves the synchronization of access resources between multiple threads.

characteristics of volatile non-atoms
public class MyThread1 extends Thread {private volatile static int count;public void Addcount () {for (int i = 0; i < 100 ; i++) {count++;} System.out.println ("count=" +count); @Overridepublic void Run () {Addcount ();}}

public class Runtest {public static void main (string[] args) {mythread1[] myarray=new mythread1[100];for (int i = 0; i < 100; i++) {myarray[i]=new MyThread1 ();} for (int i = 0; i <; i++) {Myarray[i].start ();}}}



public class MyThread1 extends Thread {private static int count;//needs to be static to achieve the sync effect public synchronized static void Addcoun T () {for (int i = 0; i <; i++) {count++;} System.out.println ("count=" +count); @Overridepublic void Run () {Addcount ();}}




Keyword volatile is primarily used in situations where it is possible to perceive instance variables to be changed in multiple threads, and to get the most recent values used, that is, to read shared variables with multithreading.

The keyword volatile prompts the thread to read the variable from shared memory every time, rather than reading it from private memory, which guarantees the visibility of the synchronized data. However, it is important to note that if you modify the data in the instance variable, such as i++, which is i=i+1, the operation is not an atomic operation, that is, non-thread-safe. The actual steps of the expression i++ are:

    1. Reads the value of I from memory;
    2. Calculates the value of I;
    3. Writes the value of I to memory.
Therefore, volatile itself does not deal with the atomicity of data, but it forces the data to read and write in a timely manner affecting the main memory.
from the above we can draw the conclusion that:The synchronized keyword is to prevent multiple threads from executing a piece of code at the same time, which can affect program execution efficiency, while the volatile keyword has better performance than synchronized in some cases. Note, however, that the volatile keyword cannot replace the synchronized keyword because the volatile keyword does not guarantee the atomicity of the operation. In general, the following 2 conditions are required to use volatile:
1) The write operation to the variable does not depend on the current value
2) The variable is not included in the invariant with other variables


In fact, these conditions indicate that these valid values that can be written to a volatile variable are independent of the state of any program, including the current state of the variable.
In fact, my understanding is that the above 2 conditions need to ensure that the operation is atomic, so that programs that use the volatile keyword can execute correctly when concurrency occurs.


scenarios where volatile is used in Java:
Package Com.ztz.mythread;public class Singleton {Private volatile static Singleton instance = Null;private Singleton () {}p Ublic static Singleton getinstance () {if (instance==null) {synchronized (Singleton.class) {if (instance==null) instance = New Singleton ();}} return instance;}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java multi-thread volatile keyword

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.