Volatile provides a weak synchronization mechanism to ensure that variable updates are notified to other threads. Volatile variables are not cached in registers or are not visible to other processors, and therefore always return the most recently written value when reading volatile variables. The following semantics can be imagined, but volatile is a more lightweight synchronization mechanism. Volatile only ensures visibility, but does not guarantee atomicity. This means that volatile variables, such as i++, cannot be used in a composite operation.
Copy Code code as follows:
Public synchronized void SetValue (int value) {
This.value = value;
}
public synchronized int GetValue () {
return value;
}
You can use the volatile variable when all of the following conditions are true
1. Write operations on variables 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 does not incorporate invariant conditions with other state variables
3. The access variable is not required to lock