Parsing volatile keywords in java

Source: Internet
Author: User

Parsing volatile keywords in java

Volatile is often used in java multi-threaded programming. Sometimes this keyword is confused with synchronized or lock. The specific analysis is as follows:

In a multi-threaded environment, the member variable visibility problem occurs: Each thread in java has a thread stack memory space, which stores the variable information during the thread runtime, when a thread accesses a variable value, it first finds the specific content of the object's heap memory or stack storage (native data type) based on the address of the variable, then, a copy of the same value is stored in the thread stack of the current thread, and all operations on this variable have nothing to do with the variable content in the stack memory before the thread exits, the operation is a copy in the Self-thread stack. After the operation, the operation result is written back to the primary memory. If there are two threads A and B, and A colleague operates A variable x; A adds 1 to x, then the copy obtained by B may be the result of x plus 1, it may also be x. To ensure that the latest data variables in the memory are obtained, the volatile keyword must be added, in this way, each operation on x will check whether the value of the variable in the thread stack is the same as the value of the variable in the memory. If they are different, load them again.

Eg:

 

Public class ThreadSee {// t1 thread will perform corresponding operations based on the flag value, and the main thread will change the value of t1 public static void main (String [] args) throws InterruptedException {ThReadTest th = new ThReadTest (); Thread t1 = new Thread (th); t1.start (); Thread. sleep (1000); th. changeFlag (); Thread. sleep (1, 2000); System. out. println (th. getFlag () ;}} class ThReadTest implements Runnable {// load the variable to the corresponding thread stack when the thread accesses the variable, get the latest data in the memory private volatile boolean sto each operation Pflag; @ Override public void run () {int I = 0; while (! Stopflag) {I ++; System. out. println ("=" + Thread. currentThread (). getName ();} System. out. println ("Thread finish:" + I);} public void changeFlag () {this. stopflag = true; System. out. println (Thread. currentThread (). getName () + "************");} public boolean getFlag () {return stopflag ;}}

If the above Code is removed from volatile, It will be executed in an endless loop.

 

However, volatile cannot guarantee thread-safe synchronization.

Eg:

 

public class ThreadSave implements Runnable{    static ThreadSave sync = new ThreadSave();    static volatile int j=0;    //Lock  lock =new ReentrantLock();    public  void inscane(){       // lock.lock();        for(int i=0;i<10000000;i++){            j++;        }     //   lock.unlock();    }    @Override    public void run() {        inscane();    }    public static void main(String[] args) throws InterruptedException {        Thread t1 = new Thread(sync);        Thread t2 = new Thread(sync);        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println(j);    }}
The execution result based on the above Code is not expected to be 20000000,

 

 

For variables modified by volatile, the jvm VM only ensures that the value loaded from the primary memory to the thread's working memory is up to date.

For example, if thread 1 and thread 2 are performing the read and load operations on the thread stack and main memory and find that the count value in the main memory is 5, the latest value will be loaded.

After the thread 1 heap count is modified, it will be written to the main memory, and the count variable in the main memory will change to 6

Thread 2 because the read and load operations have been performed, after the operation, the variable value of the main memory count will also be updated to 6

As a result, concurrency still exists after the two threads are modified with the volatile keyword in a timely manner.

To sum up:

Volatile only ensures that the thread performs such an action to check whether the variable value of the current thread stack is the same as the data value in the main memory. Lock or synchronized ensures that only a single thread enters the method at a certain time point to ensure thread security.

Therefore, if multiple threads modify a volatile variable, there is no actual logic significance. If a thread modifies the variable values that other threads depend on, this is useful.

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.