I'm struggling with some concurrent legacy code and wonder whether stopLatch
and/or mode
should be volatile
:
public class MyClass {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private MyModeEnum mode = MyModeEnum.NONE;
private CountDownLatch stopLatch;
public synchronized void start(final MyModeEnum mode) {
assert mode != null && mode != MyModeEnum.NONE;
if (isRunning()) {
// Throw an exception.
}
this.mode = mode;
stopLatch = new CountDownLatch(1);
executor.execute(() -> {
try {
// Pre and post operations not under control around stopLatch.await().
} catch (final Exception e) {
stop();
// Further exception handling.
} finally {
MyClass.this.mode = MyModeEnum.NONE;
}
});
}
public synchronized void stop() {
if (!isRunning()) {
return;
}
stopLatch.countDown();
}
public boolean isRunning() {
return mode != MyModeEnum.NONE;
}
public MyModeEnum getMode() {
return mode;
}
}
Elaborate explanation very appreciated.
EDIT: I wasn't able to boil down general questions/answers such as When exactly do you use the volatile keyword in Java? to this particular problem.