I've read about the 'status flag' pattern for the volatile
usage.
It says that I can use the volatile
without any sync if the status flag doesn't depend on any other state. It will guarantee the visibility of the flag for other threads. Moreover, write to the boolean is atomic.
But in the other related question it's said that it's safe to use the volotile
when only one thread can modify the flag. Otherwise, I need to use any synchronization or AtomicBoolean
.
In my example, I have the stopped
flag, but it could be modified more than from within one thread: methods stop()
and continue()
. The doSmth()
doesn't update any states. If assume that it's OK not to do work when the stop()
was invoked right after the continue()
method, would be the code threadsafe?
class MyClass {
private volatile boolean stopped;
public void doWork() {
while(!stopped) {
doSmth();
}
}
public void stop() {
stopped = true;
}
public void continue() {
stopped = false;
}
}
As for me, it should. Could you please clarify if I'm wrong?