Notes for using the volatile keyword

  • 2020-06-07 04:27:59
  • OfStack

The Volatile variable has the visibility properties of synchronized, but not the atomic properties. This means that the thread can automatically find the latest value of the volatile variable. Volatile variables can be used to provide thread safety, but only for a very limited set of use cases: there are no constraints between multiple variables or between the current value of a variable and its modified value. Therefore, using volatile alone is not sufficient to implement a counter, a mutex, or any invariant associated with multiple variables.

The volatile keyword is one of the weaker synchronization mechanisms in Java. Why is it called weak?

Before we understand this, let's take a look at two mechanisms that java must follow when doing synchronization:

1. Visibility: when one thread modifies a Shared variable, another thread can read the modified value.

2, atomicity: refers to indivisible, here refers to the process of program execution, an operation can not be interrupted, is an atomic operation.

The volatile keyword does not guarantee atomicity, only visibility, so it cannot be used for synchronization in general. However, it can be used for synchronization when two specific conditions are met:

1. The operation result does not depend on the current value of the variable, or the thread with only one can be guaranteed to modify the value of the variable.

2. Variables do not need to participate in invariant constraints together with other state variables

Ex. :


volatile boolrean flag;
public void close(){
    flag = true;
}
public void open(){
   while(!flag){
    ...
   }
}

At this point, the execution of open() method depends on the value of flag, so synchronization must be used. However, it is tedious to use the synchronized keyword or other methods to synchronize, so the situation meets the above two conditions, so the volatile keyword can be used for synchronization.

volatile Keyword principle:

Variables modified by volatile are not cached in registers or anywhere else, and each write is directly written to main memory, and each read is read from main memory. So visibility is guaranteed.


Related articles: