Java threading and synchronization ordering: given two anonymous threads appending to StringBuffers with cross locks, what can be said about the output order? public class Test {\n public static void main(String[] args) {\n final StringBuffer a = new StringBuffer();\n final StringBuffer b = new StringBuffer();\n new Thread(){ public void run(){ System.out.print(a.append("A")); synchronized(b){ System.out.print(b.append("B")); } } }.start();\n new Thread(){ public void run(){ System.out.print(b.append("C")); synchronized(a){ System.out.print(a.append("D")); } } }.start();\n }\n}

Difficulty: Medium

Correct Answer: Indeterminate output

Explanation:


Introduction / Context:
This question assesses understanding of concurrency interleavings and synchronization granularity. Two threads mutate and print two shared StringBuffers. Some operations are outside synchronized blocks, and locks are acquired on different objects in different orders.


Given Data / Assumptions:

  • Each thread first appends and prints on an unlocked buffer.
  • Each thread then synchronizes on the other buffer before appending and printing.
  • No single lock protects the whole sequence, and the program never joins the threads.


Concept / Approach:
Because operations occur partly without locks and partly with distinct locks that are acquired independently, many valid interleavings exist. Although the lock acquisition order is opposite, no deadlock occurs here because there is no nested lock acquisition overlap (each synchronized block uses only one lock and the other thread does not hold that same lock simultaneously when trying to acquire it).


Step-by-Step Solution:
First thread prints a after appending "A"; second prints b after appending "C". Either may occur first.Later, thread 1 synchronizes on b and appends "B"; thread 2 synchronizes on a and appends "D". The relative timing is not deterministic.Thus, the combined character sequence and the interleaved buffer toString() snapshots vary run to run.


Verification / Alternative check:
Run several times; observe different sequences. Add join() and enclosing synchronized blocks or a single shared lock to make ordering reproducible.


Why Other Options Are Wrong:
Options A–C propose fixed sequences, which cannot be guaranteed under concurrency without stronger synchronization.
Option E claims deadlock; however, each thread acquires only one lock at a time and releases it, so classic cyclical wait does not arise.


Common Pitfalls:
Assuming println atomicity provides ordering; assuming the JVM scheduler is deterministic; confusing lock order inversion with guaranteed deadlock.


Final Answer:
Indeterminate output

More Questions from Java.lang Class

Discussion & Comments

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