I use an ExecutorService
to execute a task. This task can recursively create other tasks which are submitted to the same ExecutorService
and those
You could use a runner that keeps track of running threads:
Runner runner = Runner.runner(numberOfThreads);
runner.runIn(2, SECONDS, callable);
runner.run(callable);
// blocks until all tasks are finished (or failed)
runner.waitTillDone();
// and reuse it
runner.runRunnableIn(500, MILLISECONDS, runnable);
runner.waitTillDone();
// and then just kill it
runner.shutdownAndAwaitTermination();
to use it you just add a dependency:
compile 'com.github.matejtymes:javafixes:1.3.0'
This really is an ideal candidate for a Phaser. Java 7 is coming out with this new class. Its a flexible CountdonwLatch/CyclicBarrier. You can get a stable version at JSR 166 Interest Site.
The way it is a more flexible CountdownLatch/CyclicBarrier is because it is able to not only support an unknown number of parties (threads) but its also reusable (thats where the phase part comes in)
For each task you submit you would register, when that task is completed you arrive. This can be done recursively.
Phaser phaser = new Phaser();
ExecutorService e = //
Runnable recursiveRunnable = new Runnable(){
public void run(){
//do work recursively if you have to
if(shouldBeRecursive){
phaser.register();
e.submit(recursiveRunnable);
}
phaser.arrive();
}
}
public void doWork(){
int phase = phaser.getPhase();
phaser.register();
e.submit(recursiveRunnable);
phaser.awaitAdvance(phase);
}
Edit: Thanks @depthofreality for pointing out the race condition in my previous example. I am updating it so that executing thread only awaits advance of the current phase as it blocks for the recursive function to complete.
The phase number won't trip until the number of arrive
s == register
s. Since prior to each recursive call invokes register
a phase increment will happen when all invocations are complete.
Use a Future for your tasks (instead of submitting Runnable
's), a callback updates it's state when it's completed, so you can use Future.isDone to track the sate of all your tasks.
If number of tasks in the tree of recursive tasks is initially unknown, perhaps the easiest way would be to implement your own synchronization primitive, some kind of "inverse semaphore", and share it among your tasks. Before submitting each task you increment a value, when task is completed, it decrements that value, and you wait until the value is 0.
Implementing it as a separate primitive explicitly called from tasks decouples this logic from the thread pool implementation and allows you to submit several independent trees of recursive tasks into the same pool.
Something like this:
public class InverseSemaphore {
private int value = 0;
private Object lock = new Object();
public void beforeSubmit() {
synchronized(lock) {
value++;
}
}
public void taskCompleted() {
synchronized(lock) {
value--;
if (value == 0) lock.notifyAll();
}
}
public void awaitCompletion() throws InterruptedException {
synchronized(lock) {
while (value > 0) lock.wait();
}
}
}
Note that taskCompleted()
should be called inside a finally
block, to make it immune to possible exceptions.
Also note that beforeSubmit()
should be called by the submitting thread before the task is submitted, not by the task itself, to avoid possible "false completion" when old tasks are completed and new ones not started yet.
EDIT: Important problem with usage pattern fixed.
Use CountDownLatch. Pass the CountDownLatch object to each of your tasks and code your tasks something like below.
public void doTask() {
// do your task
latch.countDown();
}
Whereas the thread which needs to wait should execute the following code:
public void doWait() {
latch.await();
}
But ofcourse, this assumes you already know the number of child tasks so that you could initialize the latch's count.