Java Concurrency Interview

Live coding puzzles question 179 of 180 mid

Run a task exactly once no matter how many threads call it.

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.

puzzle atomics

Quiz yourself on Live coding puzzles Suggest a correction