Java -- Role and usage of volatile keywords

Source: Internet
Author: User

Java -- Role and usage of volatile keywords

The volatile keyword is used to make all threads in the system share the variables modified by this keyword visible. It can prohibit the thread's working memory from caching variables modified by volatile.

Volatile:

1. Visibility: Java provides the volatile keyword to ensure visibility.

When a shared variable is modified by volatile, it ensures that the modified value is immediately updated to the primary storage. When other threads need to read the variable, it reads the new value from the memory.

The visibility of common shared variables cannot be guaranteed, because after the common shared variables are modified, it is not clear when they are written to the primary storage. When other threads read the shared variables, in this case, the memory may still be the old value, so visibility cannot be guaranteed.

In addition, synchronized and Lock can also ensure visibility. synchronized and Lock can ensure that only one thread obtains the Lock at the same time and then executes the synchronization code, before the lock is released, the modification to the variable is refreshed to the primary storage. This ensures visibility.

First read a piece of code. If thread 1 is executed first and thread 2 is executed later:

// Thread 1 boolean stop = false; while (! Stop) {doSomething () ;}// thread 2 stop = true;

This code is a typical piece of code. Many people may use this flag method when thread interruption occurs. But in fact, will this Code fully run correctly? Will the thread be interrupted? Not necessarily. In most cases, this code can interrupt the thread, but it may also lead to thread interruption failure (although this possibility is very small, but once this happens, it will lead to an endless loop ).

The following explains why this Code may cause thread interruption. As explained above, each thread has its own working memory during running, so when thread 1 is running, copy the value of the stop variable to your working memory.

So when thread 2 changes the value of the stop variable, but it has not been able to write it into the main memory, thread 2 is re-running to do other things, because thread 1 does not know the changes to the stop variable of thread 2, it will keep repeating.

However, modified with volatile will become different:

First, the volatile keyword is used to forcibly write the modified value to the primary storage immediately;

Second, if the volatile keyword is used, when thread 2 is modified, the cache row of the cache variable stop in the working memory of thread 1 will be invalid (if it is reflected in the hardware layer, that is, the corresponding cache row in the CPU L1 or L2 cache is invalid );

Third: Because the cache row of the stop variable in the working memory of thread 1 is invalid, when thread 1 reads the value of the stop variable again, it will read it from the main memory.

When thread 2 modifies the stop value (of course, there are two operations, namely modifying the value in thread 2's working memory and then writing the modified value to the memory ), it will invalidate the cache row of the stop variable in the working memory of thread 1. When thread 1 reads data, it will find that its own cache row is invalid, it will wait for the primary address corresponding to the cache row to be updated, and then read the latest value from the corresponding primary memory.

Then thread 1 reads the latest correct value.

 

 

2. ensure orderliness

Volatile boolean inited = false; // thread 1: context = loadContext (); inited = true; // thread 2: while (! Inited) {sleep ()} doSomethingwithconfig (context );

Make sure that context Initialization is complete.

 

3. double check

class Singleton{    private volatile static Singleton instance = null;         private Singleton() {             }         public static Singleton getInstance() {        if(instance==null) {            synchronized (Singleton.class) {                if(instance==null)                    instance = new Singleton();            }        }        return instance;    }}

 

Http://www.cnblogs.com/dolphin0520/p/3920373.html

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.