The function and usage of volatile keyword in Java _java

Source: Internet
Author: User

Volatile this keyword probably many friends have heard, perhaps also all used. Before Java 5, it was a controversial keyword, because using it in a program often resulted in unexpected results. After Java 5, the volatile keyword was able to regain its vitality.

The volatile keyword makes it possible for all threads in the system to share a variable that is decorated with this keyword, and to prevent the thread's working memory from caching volatile-decorated variables.

Volatile 2 usage Scenarios:

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

When a shared variable is volatile decorated, it guarantees that the modified value is immediately updated to main memory, and that it reads the new value in memory when another thread needs to read it.

Ordinary shared variables do not guarantee visibility, because when the normal shared variable is modified and when it is written to main memory is indeterminate, when other threads go to read, the memory may still be the original old value, so the visibility can not be guaranteed.

In addition, visibility can be ensured through synchronized and lock, and synchronized and lock ensure that only one thread acquires the lock at the same time and then executes the synchronization code, and the modifications to the variable are flushed to main memory before the lock is released. Therefore, visibility can be guaranteed.

Read a piece of code first, if thread 1 executes first, thread 2 executes after:

Thread 1
Boolean stop = false;
while (!stop) {
dosomething ();
}
Thread 2
stop = true;

This code is a typical piece of code that many people might use when interrupting threads. But in fact, does this code run exactly right? Is it certain that the thread will be interrupted? Not necessarily, perhaps for most of the time, this code can break the thread, but it may also cause a disconnection (although this is a small possibility, it can cause a dead loop if this happens).

The following explains why this code could cause a thread to be disconnected. As explained earlier, each thread has its own working memory during the run, so thread 1 will copy the value of the stop variable to its working memory when it is running.

So when thread 2 changes the value of the stop variable, but before it can be written into main memory, and thread 2 turns to do something else, thread 1 does not know that the thread 2 changes to the stop variable, so it continues to loop.

  But with volatile it becomes different:

First: Using the volatile keyword forces the modified value to be written to main memory immediately;

Second: Use the volatile keyword, when the thread 2 is modified, will cause the thread 1 in the working memory of the cache variable stop cache line invalid (reflected to the hardware layer, is the CPU L1 or L2 cache of the corresponding cache line invalid);

Third: Because the cached row of the cached variable stop in thread 1 's working memory is invalid, thread 1 reads the main memory again when the value of the variable stop is read.

Then thread 2 modifies the stop value (there are 2 operations here, of course). Modifying the value in the thread 2 working memory and then writing the modified value to memory invalidates the cached row of the cached variable stop in the working memory of thread 1, and then the thread 1 reads and finds that its own cache line is invalid. It waits for the main memory address of the cache row to be updated, and then reads the most recent value to the corresponding main memory.

So thread 1 reads the latest correct value.

2. Ensure the order of the

Volatile Boolean inited = false;
Thread 1: Context
= Loadcontext (); 
Inited = true; 
Thread 2: While
(!inited) {sleep
()
}
dosomethingwithconfig (context);

Make sure the context is initialized.

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

The above is a small series to introduce the Java volatile keyword role and usage of detailed, hope to help everyone, if you have any questions please give me a message, small set will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.