Protecting shared state: which change ensures Foo.data remains consistent under concurrency?\n\npublic class SyncTest {\n public static void main(String[] args) {\n Thread t = new Thread() {\n Foo f = new Foo();\n public void run() { f.increase(20); }\n };\n t.start();\n }\n}\nclass Foo {\n private int data = 23;\n public void increase(int amt) {\n int x = data;\n data = x + amt;\n }\n}

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:

  • Field data is mutable shared state.
  • Method increase(int) performs a non-atomic read-modify-write.
  • Multiple threads may call increase concurrently in realistic scenarios.


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:

Change signature to public synchronized void increase(int amt).This serializes all calls on the same Foo object.Now read x = data and write data = x + amt occur without interleaving.Visibility is guaranteed when threads enter/exit the monitor.


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:

  • Synchronizing run() or at the call site is fragile and not enforced for all callers.
  • No runtime exception occurs by default.
  • volatile alone does not make the compound operation atomic.


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

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion