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