Live coding puzzles question 179 of 180 mid
Run a task exactly once no matter how many threads call it.
- A
volatile boolean doneflag checked before running - Correct:
AtomicBoolean.compareAndSet(false, true), or class initialisation, orsynchronizedwith a double check - A
ThreadLocalflag Collections.synchronizedSetof task names
private final AtomicBoolean started = new AtomicBoolean();
void start() {
if (started.compareAndSet(false, true)) {
doStart(); // exactly one caller reaches here
}
}
The wrong version is a volatile boolean: check and set are two operations, so two threads can both
see false. That is the check-then-act race in its smallest possible form, and it is the whole point of
the question.
Worth adding: other callers return immediately without knowing whether initialisation has finished.
If they must wait for it, add a CountDownLatch the winner counts down and everyone else awaits.