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:
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:
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:
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
Discussion & Comments