volatile applicable scenarios

I have always been confused by the use of volatile. Today I read a blog post about volatile and share it.

volatile applicable scenarios

Volatile is suitable for scenarios where atomicity is not guaranteed, but visibility is required. A typical use case is to use it to decorate the status flag used to stop the thread. As follows

1
2
3
4
5
6
7
8
9
10
11
12
13
boolean isRunning = false ;
 
public void start () {
new Thread( () -> {
while (isRunning) {
someOperation();
}
}).start();
}
 
public void stop () {
isRunning = false ;
}

 

In this implementation, even if other threads set isRunning to false by calling the stop() method, the loop does not necessarily end immediately. The volatile keyword can be used to ensure that the while loop gets the latest status of isRunning in time to stop the loop and end the thread in time.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326612909&siteId=291194637