问题
Assume the following code
public class Singleton {
boolean shuttingDown = false;
void action() {
if (shuttingDown) {
throw new RuntimeException("already shutting down");
}
// do some more stuff
}
// Called by a single thread only
void onShutDown() {
shuttingDown = true;
// perform some more actions to remedy the class
}
}
Basically I want to block all upcoming calls to action() with an exception.
I know that setting shuttingDown is an atomic operation. However the question is if I would need to make shuttingDown volatile to make the change visible to the other threads, which might be re-used from a thread pool.
I saw this oracle tutorial and also the javadoc on AtomicBoolean. However the latter uses volatile, too. I set the value only once in a single thread, so I don't need the locking mechanisms provided by AtomicBoolean. I just want to make the change visible to all threads as soon as the variable is updated.
As far as I understand the oracle tutorial, the update operation is atomic, that is no other thread can intecept while setting the value. The question is, when will the updated value be populated to the other threads (if at all?).
回答1:
The short answer is yes, you must make it volatile.
Although the operation is atomic, for it to be guaranteed visible to other threads you need to establish a happens before relationship. Volatile is the simplest way to do this.
来源:https://stackoverflow.com/questions/28304116/is-volatile-needed-for-a-lazy-boolean-shutdown-flag-in-java