
Sponsored
Sponsored
This approach employs semaphores to control the execution order of methods. Since semaphores are synchronization constructs that can be used to control access to a common resource in a concurrent system, we can use them to gate the execution of 'second' and 'third' methods until 'first' and 'second' have completed, respectively. The semaphore for 'second' starts at 0 and is incremented by 'first', allowing 'second' to run. Similarly, 'third' can proceed only after 'second' increments its semaphore.
Time Complexity: O(1) for each method call. Space Complexity: O(1).
1import java.util.concurrent.Semaphore;
2
3public class Foo {
4 private Semaphore secondSemaphore = new Semaphore(0);
5 private Semaphore thirdSemaphore = new Semaphore(0);
6
7 public void first(Runnable printFirst) throws InterruptedException {
8 printFirst.run();
9 secondSemaphore.release();
10 }
11
12 public void second(Runnable printSecond) throws InterruptedException {
13 secondSemaphore.acquire();
14 printSecond.run();
15 thirdSemaphore.release();
16 }
17
18 public void third(Runnable printThird) throws InterruptedException {
19 thirdSemaphore.acquire();
20 printThird.run();
21 }
22}In Java, the Semaphore class from java.util.concurrent is used similarly to control the flow of execution. The first method runs and increments the semaphore for the second method, allowing it to proceed only after first is complete. second then releases the semaphore for third once it has run.
This approach leverages locks and condition variables to achieve the desired execution order. By associating each method with a condition variable, the appropriate method waits (and releases lock) until the previous condition is signaled, facilitating the required sequence.
Time Complexity: O(1) for each method call. Space Complexity: O(1).
1class Foo {
2 constructor() {
In JavaScript, since there's no native semaphore or lock, we utilize promises for sequencing - each method holds a promise chain, ensuring the sequence is maintained. Each call ensures that the previous methods have completed execution before proceeding.