Synchronizers: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most synchronizer bugs do not crash. The program simply hangs: some thread waits for a count, a permit or a party that will never come. Each kind of hang has a typical cause and a short, reliable fix.
Mistake 1: a latch count that never reaches zero
A latch waits until as many countDown() calls have happened as its starting count. If even one call is missing, await() blocks forever.
Example 1 · Mistake: the latch counts a cancelled order
import java.util.List;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class OrderLatchDemo { static List<String> orders = List.of("ORD-1", "ORD-2 (cancelled)", "ORD-3");
static void run(boolean fixed) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(3); long toPack = fixed ? orders.stream().filter(o -> !o.contains("cancelled")).count() : orders.size(); // bug: counts the cancelled order CountDownLatch packed = new CountDownLatch((int) toPack);
for (String order : orders) { if (order.contains("cancelled")) { continue; // no task, so no countDown } pool.submit(() -> { try { // pack the order... } finally { packed.countDown(); } }); }
if (packed.await(300, TimeUnit.MILLISECONDS)) { System.out.println((fixed ? "Fixed: " : "Buggy: ") + "all orders packed"); } else { System.out.println((fixed ? "Fixed: " : "Buggy: ") + "timed out, count still " + packed.getCount()); } pool.shutdown(); }
public static void main(String[] args) throws InterruptedException { run(false); run(true); }}Buggy: timed out, count still 1 Fixed: all orders packed
What this code does
- The buggy latch starts at 3 (all orders), but only 2 tasks are started because the cancelled order is skipped. The count stops at 1 and plain
await()would hang forever. - The timed
awaitturns the hang into a clear line showing how many count-downs are missing. The fix sets the count to the number of tasks really submitted. countDown()sits infinally, so a task that throws while packing still counts. This output assumes the quick threads finish well inside the timeout; on a very slow or busy computer the result can differ.
The usual causes: the count was set from a list but some items were skipped, a task threw before countDown(), or a task returned early.
The fix has three parts. Set the count to the number of tasks you really start. Call countDown() in finally, so every path counts. In code that talks to slow or unreliable parts, use await(timeout, unit) so a missing count shows up as a clear message instead of a frozen app.
Mistake 2: forgetting to release a permit
A permit taken with acquire() and never returned is leaked. Each leak lowers the limit by one, until nobody can get in although the resource is idle.
Example 2 · Mistake: an early return leaks permits
import java.util.Map;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;
class ResultService { private final Semaphore slots = new Semaphore(2); private final Map<String, String> cache = Map.of("R2", "PASS", "R3", "FAIL"); private final boolean safe;
ResultService(boolean safe) { this.safe = safe; }
String result(String roll) throws InterruptedException { if (!slots.tryAcquire(100, TimeUnit.MILLISECONDS)) { return roll + ": server busy"; } if (!safe) { if (cache.containsKey(roll)) { return roll + ": " + cache.get(roll) + " (cache)"; // permit never released } String r = roll + ": PASS (database)"; slots.release(); return r; } try { if (cache.containsKey(roll)) { return roll + ": " + cache.get(roll) + " (cache)"; } return roll + ": PASS (database)"; } finally { slots.release(); // every path } }}
public class EarlyReturnLeakDemo { public static void main(String[] args) throws InterruptedException { String[] rolls = {"R1", "R2", "R3", "R4"}; for (boolean safe : new boolean[] {false, true}) { System.out.println(safe ? "With finally:" : "Without finally:"); ResultService service = new ResultService(safe); for (String roll : rolls) { System.out.println(" " + service.result(roll)); } } }}Without finally: R1: PASS (database) R2: PASS (cache) R3: FAIL (cache) R4: server busy With finally: R1: PASS (database) R2: PASS (cache) R3: FAIL (cache) R4: PASS (database)
What this code does
- Without
finally, the two cache hits return early and keep their permits. After R3 both permits are gone, so R4 is told "server busy" even though nobody is using the server. - This shows up in production as a service that works for a while and then refuses everyone. Restarting "fixes" it, which hides the real cause.
- With
try/finally, every path returns the permit, so R4 is served.
The usual causes are an exception, an early return (for example when a cached answer is found) or a release() that sits only in the success branch.
The fix is the standard shape: acquire() just before try, release() in finally. The opposite bug is just as bad: calling release() after a failed tryAcquire, which adds permits and quietly raises the limit.
Mistake 3: wrong party count on a barrier
A CyclicBarrier(n) trips when exactly n parties have arrived. A wrong n either hangs the threads or trips the barrier too early.
Example 3 · Mistake: too few and too many parties
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.concurrent.atomic.AtomicInteger;
public class PartyCountDemo { static void startAll(int threads, CyclicBarrier barrier, AtomicInteger timeouts, AtomicInteger broken) throws InterruptedException { Thread[] ts = new Thread[threads]; for (int i = 0; i < threads; i++) { ts[i] = new Thread(() -> { try { barrier.await(300, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { timeouts.incrementAndGet(); } catch (BrokenBarrierException e) { broken.incrementAndGet(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "worker-" + (i + 1)); ts[i].start(); } for (Thread t : ts) { t.join(); } }
public static void main(String[] args) throws InterruptedException { AtomicInteger trips = new AtomicInteger(); AtomicInteger timeouts = new AtomicInteger(); AtomicInteger broken = new AtomicInteger();
CyclicBarrier tooFew = new CyclicBarrier(2, trips::incrementAndGet); startAll(4, tooFew, timeouts, broken); System.out.println("4 threads, 2 parties: action ran " + trips.get() + " times (wanted 1)");
CyclicBarrier tooMany = new CyclicBarrier(3); startAll(2, tooMany, timeouts, broken); System.out.println("2 threads, 3 parties: TimeoutException " + timeouts.get() + ", BrokenBarrierException " + broken.get());
trips.set(0); CyclicBarrier right = new CyclicBarrier(4, trips::incrementAndGet); startAll(4, right, timeouts, broken); System.out.println("4 threads, 4 parties: action ran " + trips.get() + " time"); }}4 threads, 2 parties: action ran 2 times (wanted 1) 2 threads, 3 parties: TimeoutException 1, BrokenBarrierException 1 4 threads, 4 parties: action ran 1 time
What this code does
- Too few parties: 4 threads on a barrier of 2 make two separate trips, so the "merge everyone" action runs twice, each time on only half of the work.
- Too many parties: 2 threads can never fill a barrier of 3. Without the timeout they would wait forever; with it, one thread times out and breaks the barrier, and the other gets
BrokenBarrierException. - With the party count equal to the thread count, the barrier trips once and the action sees all four results. This output assumes the quick threads finish well inside the timeout; on a very slow or busy computer the result can differ.
With too many parties, the real threads all wait for a thread that does not exist, and plain await() hangs. With too few, the barrier trips early: the barrier action runs on half the data, and in the last round the extra threads wait for partners that never come.
Create the barrier from the same number you use to start the threads, such as new CyclicBarrier(workers.length, action). A timed await turns a wrong count into a TimeoutException you can see.
Mistake 4: a barrier inside a thread pool that is too small
A barrier needs all its parties running at the same time. In a fixed pool of 2 threads, a barrier of 3 can never trip, even though every line looks correct.
Example 4 · Mistake: a barrier of 3 in a pool of 2
import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;import java.util.concurrent.atomic.AtomicInteger;
public class PoolTooSmallDemo { static void run(int poolSize) throws InterruptedException { CyclicBarrier barrier = new CyclicBarrier(3); AtomicInteger passed = new AtomicInteger(); AtomicInteger timedOut = new AtomicInteger(); AtomicInteger broken = new AtomicInteger(); ExecutorService pool = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < 3; i++) { pool.submit(() -> { try { barrier.await(300, TimeUnit.MILLISECONDS); passed.incrementAndGet(); } catch (TimeoutException e) { timedOut.incrementAndGet(); } catch (BrokenBarrierException e) { broken.incrementAndGet(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("Pool of " + poolSize + ": passed " + passed.get() + ", timed out " + timedOut.get() + ", broken " + broken.get()); }
public static void main(String[] args) throws InterruptedException { run(2); run(3); }}Pool of 2: passed 0, timed out 1, broken 2 Pool of 3: passed 3, timed out 0, broken 0
What this code does
- With 2 pool threads, the first two tasks block in
await()and the third task cannot start. One wait times out and breaks the barrier, the other waiting task getsBrokenBarrierException, and the third task finally runs only to find the barrier already broken. - Without the timeout, the two tasks would wait forever and the pool would never finish: a deadlock caused by the pool size, not by the barrier code.
- With 3 threads for 3 parties, all three tasks run at once and pass the barrier. This output assumes the quick threads finish well inside the timeout; on a very slow or busy computer the result can differ.
Two tasks take both threads and wait in await(), and the third task stays in the queue because no thread is free. This is a deadlock.
Give the pool at least as many threads as the barrier has parties, or run the parties on their own threads. The same trap exists with a latch when pool tasks wait for other tasks that are still queued behind them.
Finish up
Mark complete & continue
Next: Why CompletableFuture?