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

How to apply volatile in java

WBOY
Release: 2023-05-04 11:46:28
forward
1497 people have browsed it

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
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template