Java concurrency and synchronization scope: predict the output and determinism of this program. class Happy extends Thread { final StringBuffer sb1 = new StringBuffer(); final StringBuffer sb2 = new StringBuffer(); public static void main(String args[]) { final Happy h = new Happy(); new Thread() { public void run() { synchronized (this) { h.sb1.append("A"); h.sb2.append("B"); System.out.println(h.sb1); System.out.println(h.sb2); } } }.start(); new Thread() { public void run() { synchronized (this) { h.sb1.append("D"); h.sb2.append("C"); System.out.println(h.sb2); System.out.println(h.sb1); } } }.start(); } }

Difficulty: Medium

Correct Answer: Output is non-deterministic due to concurrent interleaving

Explanation:


Introduction / Context:
This question checks your understanding of Java threading, synchronization scopes, and why using synchronized(this) on different objects does not coordinate access across threads. It also touches on StringBuffer being thread-safe for individual operations but not making multi-object sequences atomic.



Given Data / Assumptions:

  • Two anonymous Thread instances mutate shared fields h.sb1 and h.sb2.
  • Each thread uses synchronized(this) where this refers to the anonymous Thread object, not the shared Happy instance.
  • Each thread appends to sb1 and sb2 and then prints them in different orders.


Concept / Approach:
Synchronization must use the same monitor to enforce mutual exclusion. Here, each synchronized block locks a different monitor (the respective Thread instance), so there is no inter-thread coordination. Although StringBuffer methods are synchronized, they only serialize access per buffer method call, not across the two-buffer sequence. Therefore, the order of appends and prints can interleave in many ways.



Step-by-Step Solution:

Thread-1: append A to sb1, B to sb2, then print sb1 and sb2.Thread-2: append D to sb1, C to sb2, then print sb2 and sb1.Because monitors differ, these four appends and four prints can interleave arbitrarily.Final contents will include A and D in sb1, B and C in sb2, but line order is not guaranteed.


Verification / Alternative check:
Replace synchronized(this) with synchronized(h) (or a dedicated common lock) to serialize both threads around the complete sequence; then you would see a predictable grouping of prints.



Why Other Options Are Wrong:

  • AB… fixed-line options assume a deterministic schedule which is not enforced.
  • The code does compile; syntax and imports are fine.


Common Pitfalls:
Assuming synchronized anywhere implies global serialization; confusing StringBuffer’s internal synchronization with atomic multi-step logic; locking on the wrong monitor.



Final Answer:
Output is non-deterministic due to concurrent interleaving

More Questions from Threads

Discussion & Comments

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