Challenge 3: Making Repository<T> Thread-Safe — Possible Solution ==================================================================== // What would need to change in the capstone's Repository to make // it safe for concurrent access from multiple threads, per java2-5: // // As written, Repository wraps a plain HashMap. HashMap // itself is NOT thread-safe -- concurrent put() calls from multiple // threads can corrupt its internal structure, not just produce lost // updates the way the chapter's own Counter example did. This is a // more severe version of the exact race-condition class java2-5 // demonstrated with a shared int counter. // // The straightforward fix, following java2-5's own guidance directly, // would be to mark save() and find() as synchronized, so every // read/write to the underlying map is serialized through the same // intrinsic lock: // // public synchronized void save(String key, T item) { ... } // public synchronized Optional find(String key) { ... } // // A better fix, reaching for java2-5's own recommended higher-level // tool instead of hand-rolled synchronized, would be to replace the // plain HashMap with a ConcurrentHashMap from java.util.concurrent -- // a map specifically designed for safe concurrent access without // requiring every caller to synchronize manually at all: // // private final Map items = new ConcurrentHashMap<>(); // // Either approach only protects Repository's own internal map. // java2-5's warn-box applies here too: if some OTHER, unsynchronized // code elsewhere directly manipulated a Product's mutable state (were // Product not an immutable record per java2-7), that would remain a // separate, unprotected risk entirely outside Repository's control. WHY THIS WORKS AS AN ANSWER ------------------------------ This correctly identifies that the underlying HashMap is unsafe under concurrent access, proposes both the chapter's own synchronized approach and java2-5's preferred higher-level ConcurrentHashMap alternative, and explicitly ties the risk back to java2-5's own race- condition and partial-synchronization material.