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:
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:
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