Home  >  Article  >  Java  >  How to apply volatile in java

How to apply volatile in java

WBOY
WBOYforward
2023-05-04 11:46:281447browse

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete