H2ONaCl H2ONaCl - 1 month ago 12
Java Question

synchronization as an alternative to a volatile declaration

In this tutorial (link) on Java's volatile declaration it is said that the volatile declaration can be an alternative to synchronization.

The author's example of a use of the volatile declaration:

volatile boolean shutdownRequested;

...

public void shutdown() { shutdownRequested = true; }

public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}


My naive implementation of synchronization would be:

volatile boolean shutdownRequested;

...

synchronized public void shutdown() { shutdownRequested = true; }

synchronized public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}


It seems that if thread A invokes
shutdown
while thread B has already invoked and is running
doWork
it would seem that thread B will continually lock execution, because it is a loop. This seems to give no opportunity for thread A to access the boolean. What did the author have in mind as the synchronized alternative to a volatile declaration?

Answer

The // do stuff part would be outside the synchronized block. For example, instead of doWork being synchronized and having while (!shutdownRequested), you might have while (!getShutDown()) where getShutDown is the synchronized method that returns shutdownRequested.