Challenge 2: Fixing the Race Condition with synchronized — Possible Solution ==================================================================== FixedRaceDemo.java: public class FixedRaceDemo { static class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i < 100_000; i++) { counter.increment(); } }; Thread t1 = new Thread(task); Thread t2 = new Thread(task); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Final count: " + counter.getCount()); } } Output (reliable across every run): Final count: 200000 Explanation: Marking increment() synchronized means each call must acquire the Counter instance's intrinsic lock before running count++, and release it afterward. Since both threads call increment() on the SAME Counter object, they're contending for the same lock -- only one thread can execute the read-modify-write sequence at a time, eliminating the interleaving that caused lost updates in Challenge 1. The result is now exactly 200,000 every time, not just usually close to it. WHY THIS WORKS AS AN ANSWER ------------------------------ This applies the chapter's own stated fix -- the synchronized keyword -- directly to the method responsible for the race condition, and the now-deterministic 200,000 result demonstrates the lock genuinely serializes access rather than merely reducing the frequency of lost updates.