In some cases, the performance of the volatile keyword is better than that of synchronized, but it should be noted that the volatile keyword cannot replace the synchronized keyword, because the volatile keyword cannot guarantee the atomicity of the operation.
Application scenarios
1. Volatile variables can only be used to replace locks in limited circumstances. Variables do not depend on the current value.
2. This variable is not included in the invariant form of other variables.
Example
volatile boolean shutdownRequested; ... public void shutdown() { shutdownRequested = true; } public void doWork() { while (!shutdownRequested) { // do stuff } }
The above is the detailed content of How to apply volatile in java. For more information, please follow other related articles on the PHP Chinese website!