In this Q&A, we'll go over a few ways to execute a task after the completion of dependent or pre-requisite tasks.
Pre Java 5, one could use combination of synchronization, wait and notifyAll to to achieve the above. But there are more language supported synchronization constructs now. We'll go over them here.
Pre Java 5, one could use combination of synchronization, wait and notifyAll to to achieve the above. But there are more language supported synchronization constructs now. We'll go over them here.
Option - I Use CountDownLatch
Count down latch works as below:
- Initialize the counter to the # of tasks that has to be completed
- after each task completion count down the common latch object
- one or more threads wait for the completion of all the pre-requisite tasks. Once tasks are completed, awaiting thread(s) will continue with its execution.
See sample usage here
Option - II Use CyclicBarrier
CyclicBarrier works like every task has to wait until all of them have completed the pre-requisite tasks. It works as below
- Initialize the barrier object with # of parties or tasks
- each thread starts waiting on the common barrier once their pre-requisite is met
- when all of the threads arrive at the barrier point ( threads waiting equals # of parties ) then all threads are released.
See sample usage here. Also note that unlike CountDownLatch, CyclicBarrier objects can be re-initialized.
Option - III Use Phaser
Java provides another construct Phaser which can be used to create parties (or tasks) to the barrier dynamically and await on them. It works by
- Creating a Phaser object first. Phaser represents a barrier or a phase of task execution
- Each task registers itself as a party to the barrier by calling the register() method
- Tasks arrive the barrier point by calling one of the await() methods
- Tasks no longer part of the task execution can deregister() from the Phaser
- Tasks no longer part of the task execution can deregister() from the Phaser
See sample usage here
Option - IV Use Thread join
If dependent task can be represented as a thread, you can use thread join() to wait for the dependent task or thread to complete.
Thread t = new Thread();
t. start();
t.join(); // wait for task or thread completion
Comments
Post a Comment