The volatile keyword in Java

Today I met this code

class someClass {

  // ...    
  private volatile int a;
  // ...

}

The question is, what is volatile in this context?

Author: Имя Фамилия, 2011-01-10

7 answers

The volatile modifier imposes some additional conditions on reading / writing a variable. It is important to understand two things about volatile variables:

  1. The read/write operations of a volatile variable are atomic.
  2. The result of the operation of writing a value to a volatile variable by one thread becomes visible to all other threads that use this variable to read the value from it.

It seems that for a person asking a question like yours, it is enough know these two things.

 60
Author: a_gura, 2014-04-20 19:25:57

This means that the value of the variable will be "always read". For example, in multithreaded applications, one thread read the value a=1, passed control to another thread, which changed the value to a=2, and then control returned. So, without volatile, the value of a for the first thread will be 1, because the first thread "remembers" that a=1, with volatile - 2, because the first thread will read the value again and get the already changed one.

 36
Author: Georgy, 2019-05-25 00:26:08
  • The variable has a master copy, plus a copy for each thread that uses it. The master copy syncronizes with the local one a copy of the thread when entering/exiting the synchronized block. Sometimes, for example, an empty synchronized(lock) block){} makes sense.

  • Variables with the volatile modifier do not have local copies. All threads work with the master copy.

 24
Author: bbk75, 2011-01-19 22:43:46

Here is the definition given in the article "Java Multithreading" on the site http://alfalavista.ru.

Defining a variable with the keyword volatile means that the value of this variable can be changed by other threads. To to understand what volatile does, it is useful to understand how threads handle normal variables.

For performance reasons, the Java language specification allows the JRE to store a local copy of a variable for each flow rate, which refers to it. Such" local " copies of variables resemble a cache and help the thread avoid accessing the main memory. each time you want to get the value of a variable. At startup two threads, one of them reads the variable A as 5, and the second reads it as 10. If the value of variable A has changed from 5 to 10, the first thread will not know about the change and will store the wrong value of A. But if the variable A is marked as volatile, then when would the thread not read the value of A, it will access the master copy of A and read its current value. A local stream cache makes sense if variables in your applications will not be changed from the outside.

If a variable is declared as volatile, it means that it can be changed by different threads. It is natural to expect that the JRE will provide some form of synchronization of such volatile variables. The JRE does implicitly provide synchronization when accessing volatile variables, but with one very big caveat: reading a volatile variable and writing to a volatile variable are synchronized, but non ― atomic operations are not.

 14
Author: tarasula, 2015-08-16 20:44:32

For object references, you don't need to write volatile. Am I right?

For example, when we use the Singleton pattern in a multithreaded application where we apply synchronization and want synchronization to occur only once when initializing an object, and not every time we call getInstance (), then we use the volatile modifier for the object reference:

public class Singleton {
    private static volatile Singleton instance;
    private Singleton(){
    }
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}
 4
Author: Eugene Goliuk, 2016-04-06 06:17:02

volatile - literally means volatile, fickle, changeable

In the context of programming, this means that the value of a variable can change unexpectedly, so you should not rely on the values of this variable, for example, if the code says:

private volatile int i;
// через некоторое время
i=0;
while(i < 10) {
  //blah-blah
  i++;
}

This does not mean that the loop will end exactly after 10 steps...

It may well happen that during the execution of the loop, the value of the volatile variable will be unexpected change (or may not change) ...

 4
Author: Barmaley, 2017-01-13 06:02:49

Volatile-tells the thread that the variable can change, and informs the thread to refer to the latest version, not the hashed copy, and distribute the changes in a timely manner.

A "volatile" data member informs a thread, both to get the latest value for the variable (instead of using a cached copy) and to write all updates to the variable as they occur.

 2
Author: Aliaksandr Shpak, 2019-06-29 18:33:59