Challenge 3: Making Repository Thread-Safe — Possible Solution ==================================================================== // What would need to change in the capstone's Repository to make // it safe for concurrent access from multiple threads, and how the // C# tools compare to java2-8's own equivalent challenge: // // As written, Repository wraps a plain List. Like Java's // HashMap (java2-8's own concern), List is NOT thread-safe -- // concurrent Add()/Remove() calls from multiple threads can corrupt // its internal structure, not merely produce lost updates. // // The direct C# parallel to java2-8's synchronized-method fix would // be to wrap each method's body in a `lock` block against a private // object: // // private readonly object _lock = new(); // public void Add(T item) { lock (_lock) { _items.Add(item); } } // // This is C#'s own manual mutual-exclusion primitive -- conceptually // identical to Java's synchronized keyword, just requiring an // explicit lock object rather than using the instance's own built-in // intrinsic lock the way Java's synchronized does automatically. // // A better fix, matching java2-8's own preferred ConcurrentHashMap // answer, would be to reach for a genuinely concurrent collection // instead of hand-rolled locking -- System.Collections.Concurrent // offers ConcurrentBag or ConcurrentQueue as real, built-in // thread-safe alternatives to List, designed specifically to avoid // needing manual locks for common operations at all. // // One genuine difference worth naming: nothing in this capstone // actually uses real multi-threading (csharp2-4's async/await // suspends the CURRENT thread without necessarily using extra // threads for I/O-bound work at all, per that chapter's own // distinction) -- so, as built, Repository genuinely has no // concurrent-access risk in THIS capstone specifically. The risk // would only become real if Task.Run() (csharp2-4's genuine // CPU-bound-parallelism tool) were introduced to run multiple // Repository operations on different thread-pool threads at the // same time. WHY THIS WORKS AS AN ANSWER ------------------------------ This correctly identifies the underlying List as unsafe under genuine concurrent access, proposes both the lock-based C# parallel to Java's synchronized and the preferred concurrent-collection alternative, and correctly notes that this specific capstone never actually introduces real multi-threading, tying the distinction back to csharp2-4's own async-vs-parallel material.