Print in Order

Easy
ConcurrencySemaphoreMutexThread CoordinationHappens-Before

Problem Statement

Given a class Foo with three methods first(), second(), and third(). Three threads will call these methods concurrently in any scheduler-determined order. Your task is to ensure that second() is always executed after first(), and third() is always executed after second(), regardless of thread scheduling.

class Foo {
    public void first(Runnable printFirst) throws InterruptedException {
        // printFirst.run() outputs "first"
    }
    public void second(Runnable printSecond) throws InterruptedException {
        // printSecond.run() outputs "second"
    }
    public void third(Runnable printThird) throws InterruptedException {
        // printThird.run() outputs "third"
    }
}

Key Entities

  • Foo: Shared object accessed by three threads simultaneously.
  • Semaphore / CountDownLatch: Synchronization primitive to establish ordering.
  • Runnable: Callback passed into each method to produce output.

Requirements

  1. Method second() must not execute until first() has completed.
  2. Method third() must not execute until second() has completed.
  3. Solution must be deadlock-free and not use busy-waiting.
  4. The class must be thread-safe regardless of how the OS schedules threads.

Asked at: Google, Amazon, Microsoft, Adobe, Apple, Bloomberg

!Constraints

- Input is a permutation of [1, 2, 3] representing the order threads call the methods. - Exactly three threads are used — one per method. - No busy-waiting (spinning loops) is allowed. - Solution must not rely on sleep() for ordering.
Output

Run or submit your code to see output here.