Print in Order
EASYDescription
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:
numsis a permutation of[1, 2, 3].
Approaches
Checkout 4 different approaches to solve Print in Order. Click on different approaches to view the approach and algorithm in detail.
Using `CountDownLatch`
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
CountDownLatchobjects,latch1andlatch2, both with a count of 1. first(): Executes its logic, then callslatch1.countDown(). This decrements the latch's count to 0, releasing any threads waiting on it.second(): First, it callslatch1.await(), which blocks the thread untillatch1's count becomes 0. After being released, it executes its logic and then callslatch2.countDown().third(): Callslatch2.await(), which blocks untilsecond()has completed and counted downlatch2. Then, it executes its logic.
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
CountDownLatchobjects,latch1andlatch2, both with a count of 1. first(): Executes its logic, then callslatch1.countDown(). This decrements the latch's count to 0, releasing any threads waiting on it.second(): First, it callslatch1.await(), which blocks the thread untillatch1's count becomes 0. After being released, it executes its logic and then callslatch2.countDown().third(): Callslatch2.await(), which blocks untilsecond()has completed and counted downlatch2. 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 Analysis
Pros and Cons
- 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().
- A
CountDownLatchcannot 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).
Code Solutions
Checking out 3 solutions in different languages for Print in Order. Click on different languages to view the code.
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 Solution
Watch the video walkthrough for Print in Order
Similar Questions
5 related questions you might find useful
Tags:
No tags found.
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.