Difficulty: Easy
Correct Answer: Declare increase(int) as synchronized to guard data
Explanation:
Introduction / Context:
The code demonstrates a read-modify-write sequence on a shared field. Without synchronization, concurrent invocations may interleave in a way that loses updates (a classic race). Ensuring integrity requires atomicity and memory visibility guarantees.
Given Data / Assumptions:
Concept / Approach:
Declaring increase as synchronized makes the entire critical section atomic with respect to a Foo instance and establishes happens-before relationships for visibility. While volatile ensures visibility, it does not make compound actions atomic. Synchronizing run() or wrapping synchronized around the call site helps only if all callers do it; encapsulating the lock in the method is safer.
Step-by-Step Solution:
Verification / Alternative check:
Another correct approach is to use AtomicInteger and data.getAndAdd(amt) which is lock-free and atomic.
Why Other Options Are Wrong:
Common Pitfalls:
Relying on volatile for compound operations; synchronizing only some call sites; ignoring visibility guarantees.
Final Answer:
Declare increase(int) as synchronized to guard data
Discussion & Comments