Introduction to volatile variables in concurrent Java programming

  • 2020-04-01 03:49:23
  • OfStack

Volatile provides a weak synchronization mechanism to ensure that variable updates are notified to other threads. Volatile variables are not cached in registers or invisible to other processors, so they always return the most recently written value when read. You can think of this as semantics, whereas volatile is a more lightweight synchronization mechanism. Volatile ensures visibility, but not atomicity. That is, you cannot use volatile variables for compound operations, such as i++.


public synchronized void setValue(int value){ this.value = value; }
public synchronized int getValue(){ return value; }

Volatile variables can only be used when all of the following conditions are met
1. Writes to variables that do not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable.
2. This variable will not be included in invariance condition with other state variables
3. There is no need to lock access variables


Related articles: