Skip to main content

Practice ยท 1 of 3

Fix the stop flag with a guaranteed edge

A broken static boolean run = true stop-flag must become correct using a **CountDownLatch** as the publication channel (protocol beats hoping): 1. static String awaitStop() starts a virtual thread that busy-reads run and returns "exited" when the flag flips false; the worker first signals ready. 2. static void requestStop() โ€” waits for ready (guaranteed hb), sets run=false, signals stopped. 3. Wire it so awaitStop() always returns "exited" because run's write happens-before the worker's final read **via the latch chain**: worker awaits stopped before its last read. Additionally implement static boolean plainFlagIsSafe() returning false โ€” documenting that a plain flag WITHOUT such an edge has no visibility guarantee.

Difficulty: advanced

Back to lesson: Practice: JMM drills