Print in Order

Easy
#1052Time: Highly efficient. Waiting threads are parked by the OS, consuming minimal resources.Space: O(1) extra space for the two `CountDownLatch` objects.1 company
Companies

Prompt

Suppose we have a class:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

 

Example 1:

Input: nums = [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: nums = [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.

 

Constraints:

  • nums is a permutation of [1, 2, 3].

Approaches

4 approaches with complexity analysis and trade-offs.

This approach utilizes java.util.concurrent.CountDownLatch, a high-level synchronization aid. A latch acts as a gate that remains closed until its internal count reaches zero. We use two latches to create a dependency chain: second() waits for the first latch, and third() waits for the second latch.

Algorithm

  • Initialize two CountDownLatch objects, latch1 and latch2, both with a count of 1.
  • first(): Executes its logic, then calls latch1.countDown(). This decrements the latch's count to 0, releasing any threads waiting on it.
  • second(): First, it calls latch1.await(), which blocks the thread until latch1's count becomes 0. After being released, it executes its logic and then calls latch2.countDown().
  • third(): Calls latch2.await(), which blocks until second() has completed and counted down latch2. Then, it executes its logic.

Walkthrough

This approach utilizes java.util.concurrent.CountDownLatch, a high-level synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. A latch is initialized with a given count. Threads can wait on the latch using await(), and they will block until the count is decremented to zero by other threads calling countDown(). We use two latches to create a dependency chain: second() waits for the first latch (released by first()), and third() waits for the second latch (released by second()).

  • Initialize two CountDownLatch objects, latch1 and latch2, both with a count of 1.
  • first(): Executes its logic, then calls latch1.countDown(). This decrements the latch's count to 0, releasing any threads waiting on it.
  • second(): First, it calls latch1.await(), which blocks the thread until latch1's count becomes 0. After being released, it executes its logic and then calls latch2.countDown().
  • third(): Calls latch2.await(), which blocks until second() has completed and counted down latch2. Then, it executes its logic.
import java.util.concurrent.CountDownLatch; class Foo {    private CountDownLatch latchForSecond;    private CountDownLatch latchForThird;     public Foo() {        latchForSecond = new CountDownLatch(1);        latchForThird = new CountDownLatch(1);    }     public void first(Runnable printFirst) throws InterruptedException {        // printFirst.run() outputs "first". Do not change or remove this line.        printFirst.run();        latchForSecond.countDown();    }     public void second(Runnable printSecond) throws InterruptedException {        latchForSecond.await();        // printSecond.run() outputs "second". Do not change or remove this line.        printSecond.run();        latchForThird.countDown();    }     public void third(Runnable printThird) throws InterruptedException {        latchForThird.await();        // printThird.run() outputs "third". Do not change or remove this line.        printThird.run();    }}

Complexity

Time

Highly efficient. Waiting threads are parked by the OS, consuming minimal resources.

Space

O(1) extra space for the two `CountDownLatch` objects.

Trade-offs

Pros

  • Highly efficient and uses very little CPU while waiting.

  • The code is clean, readable, and clearly expresses the intent of waiting for a preceding task to complete.

  • Less error-prone than manual locking with wait()/notify().

Cons

  • A CountDownLatch cannot be reset once its count reaches zero, making it unsuitable for problems requiring cyclical or reusable barriers (though this is not a limitation for the current problem).

Solutions

class Foo { private Semaphore a = new Semaphore ( 1 ); private Semaphore b = new Semaphore ( 0 ); private Semaphore c = new Semaphore ( 0 ); public Foo () { } public void first ( Runnable printFirst ) throws InterruptedException { a . acquire ( 1 ); // printFirst.run() outputs "first". Do not change or remove this line. printFirst . run (); b . release ( 1 ); } public void second ( Runnable printSecond ) throws InterruptedException { b . acquire ( 1 ); // printSecond.run() outputs "second". Do not change or remove this line. printSecond . run (); c . release ( 1 ); } public void third ( Runnable printThird ) throws InterruptedException { c . acquire ( 1 ); // printThird.run() outputs "third". Do not change or remove this line. printThird . run (); a . release ( 1 ); } }

Video walkthrough

Newsletter

One sharp idea, every week

System design and interview prep — short enough to finish.

No spam. Unsubscribe anytime.

Practice

Same difficulty — related problems to reinforce the pattern.