Challenge 3: A Partially Synchronized Class — Possible Solution ==================================================================== PartiallyProtected.java: public class PartiallyProtected { private int balance = 0; public synchronized void increment() { balance++; } // NOT synchronized -- but still reads and writes the same field public void resetIfNegative() { if (balance < 0) { balance = 0; } } // Why marking only increment() synchronized does NOT fully // protect `balance`: // // synchronized only excludes OTHER synchronized callers from // running concurrently against the SAME lock (this instance's // intrinsic lock). It does not put any kind of barrier around the // field itself. resetIfNegative() never attempts to acquire that // lock at all, so it can run at the exact same instant as a // thread that IS inside the synchronized increment() -- reading // and writing `balance` with zero coordination between the two. // // The result: balance can still be read or written by // resetIfNegative() while increment() is mid-read-modify-write on // another thread, producing the same class of lost-update/torn- // read bug Challenge 1 demonstrated -- synchronizing increment() // alone gives a false sense of safety, since ANY unsynchronized // path to the same shared state defeats the protection entirely. } WHY THIS WORKS AS AN ANSWER ------------------------------ This constructs the exact scenario the chapter's warn-box describes -- one synchronized method and one unsynchronized method both touching the same field -- and the explanation correctly identifies that synchronized only excludes other synchronized callers, not all access, which is why partial synchronization provides no real guarantee at all.