Java Machine Coding: Print Sequence with Multiple Threads
Printing a strictly ordered sequence using multiple threads is a classic FAANG concurrency screen because it instantly exposes whether you grasp inter-thread coordination. Candidates who struggle typically fall back on brittle busy-waiting loops or create deadlocks under high thread contention.
The Mistake Most Candidates Make
-
Spinning on
volatilevariables: Relying on shared flags inside tightwhileloops, burning 100% CPU core capacity through busy-waiting. -
Overusing
notifyAll()on single intrinsic locks: Waking up every dormant thread simultaneously, causing a thundering herd problem where $N-1$ threads immediately go back to sleep. -
Missing spurious wakeup guards: Using
ifinstead ofwhilearound wait checks, leading to corrupt execution order when the JVM awakens a thread unpredictably.
The Right Approach
- Core mental model: Model execution as an explicit turn-based state machine where each worker blocks on its own condition variable until specifically signaled by its predecessor.
-
Key entities/classes:
ReentrantLock,Condition[], and a sharedcurrentTurnstate integer. - Why it beats the naive approach: Target-signaling dedicated condition queues yields $O(1)$ wakeups and completely prevents CPU burn and contention overhead.
The Key Insight (Code)
lock.lock();
try {
// 1. Guard against spurious wakeups
while (currentTurn != threadId) {
conditions[threadId].await();
}
// 2. Perform work and advance state
System.out.print(number + " ");
currentTurn = (currentTurn + 1) % totalThreads;
// 3. Wake ONLY the next thread in sequence
conditions[currentTurn].signal();
} finally {
lock.unlock();
}
Key Takeaways
- Always wrap
.await()calls in awhileloop check to preserve invariants against JVM spurious wakeups. - Array-based
Conditionreferences allow deterministic, point-to-point signaling between arbitrary thread topologies. - Update sequencing state strictly within the critical section prior to firing
.signal()to ensure atomicity.
If you're prepping for interviews, I've been building javalld.com — real machine coding problems with full execution traces.
Full working implementation with execution trace available at https://javalld.com/learn/print-sequence
Top comments (0)