This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: What is the use of the volatile keyword

At work, I ran into the volatile keyword. But I don’t know much about it. I found this explanation

This article has explained the details of the keyword in question. Have you used it before or seen an example of the correct use of this keyword

answer

  1. Synchronization in Java is mostly achieved through the keywords synchronized and volatile and locking

  2. In Java, we don’t have synchronized variables. Using the synchronized keyword on a variable is illegal and can cause a compilation error. Instead of synchronized variables, we can use volatile variables, which cause threads in the JVM to read volatile values in main memory and not cache them in the local copy

  3. If a variable is not shared by multiple threads, the volatile keyword is unnecessary.

Examples of volatile use:

public class Singleton {
    private static volatile Singleton _instance; // volatile variable
    public static Singleton getInstance(a) {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = newSingleton(); }}return_instance; }}Copy the code

We create this instance the first time we use it

If we had not volatile this variable, the thread that created the singleton would not have been able to communicate with the other threads. If thread A is creating A singleton, and after the singleton is created, the CPU blows up, the other threads can’t see the instance, and they think it’s empty.

Why does this happen? Because the reader thread is not locked, the memory is not synchronized and the value of the instance has not been flushed to main memory until the writer thread comes to the synchronized block. After Volatile keywords, this is handled by Java itself, and such updates are visible to all reader threads

Conclusion: The volatile keyword can also be used for communication with multiple threads in main memory

Examples of not using volatile:

public class Singleton{    
    private static Singleton _instance;   //without volatile variable
    public static Singleton getInstance(a){   
          if(_instance == null) {synchronized(Singleton.class){  
               if(_instance == null) _instance = newSingleton(); }}return _instance;  
    }
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/1…