wait until all threads finish their work in java - java
I'm writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer data and store it in a database when all threads finished their job.
How can I do this (get alerted when all threads finished their work) ?
The approach I take is to use an ExecutorService to manage pools of threads.
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
es.execute(new Runnable() { /* your task */ });
es.shutdown();
boolean finished = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.
You can join to the threads. The join blocks until the thread completes.
for (Thread thread : threads) {
thread.join();
}
Note that join throws an InterruptedException. You'll have to decide what to do if that happens (e.g. try to cancel the other threads to prevent unnecessary work being done).
Have a look at various solutions.
join() API has been introduced in early versions of Java. Some good alternatives are available with this concurrent package since the JDK 1.5 release.
ExecutorService#invokeAll()
Executes the given tasks, returning a list of Futures holding their status and results when everything is completed.
Refer to this related SE question for code example:
How to use invokeAll() to let all thread pool do their task?
CountDownLatch
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
Refer to this question for usage of CountDownLatch
How to wait for a thread that spawns it's own thread?
ForkJoinPool or newWorkStealingPool() in Executors
Iterate through all Future objects created after submitting to ExecutorService
Wait/block the Thread Main until some other threads complete their work.
As #Ravindra babu said it can be achieved in various ways, but showing with examples.
java.lang.Thread.join() Since:1.0
public static void joiningThreads() throws InterruptedException {
Thread t1 = new Thread( new LatchTask(1, null), "T1" );
Thread t2 = new Thread( new LatchTask(7, null), "T2" );
Thread t3 = new Thread( new LatchTask(5, null), "T3" );
Thread t4 = new Thread( new LatchTask(2, null), "T4" );
// Start all the threads
t1.start();
t2.start();
t3.start();
t4.start();
// Wait till all threads completes
t1.join();
t2.join();
t3.join();
t4.join();
}
java.util.concurrent.CountDownLatch Since:1.5
.countDown() « Decrements the count of the latch group.
.await() « The await methods block until the current count reaches zero.
If you created latchGroupCount = 4 then countDown() should be called 4 times to make count 0. So, that await() will release the blocking threads.
public static void latchThreads() throws InterruptedException {
int latchGroupCount = 4;
CountDownLatch latch = new CountDownLatch(latchGroupCount);
Thread t1 = new Thread( new LatchTask(1, latch), "T1" );
Thread t2 = new Thread( new LatchTask(7, latch), "T2" );
Thread t3 = new Thread( new LatchTask(5, latch), "T3" );
Thread t4 = new Thread( new LatchTask(2, latch), "T4" );
t1.start();
t2.start();
t3.start();
t4.start();
//latch.countDown();
latch.await(); // block until latchGroupCount is 0.
}
Example code of Threaded class LatchTask. To test the approach use joiningThreads();
and latchThreads(); from main method.
class LatchTask extends Thread {
CountDownLatch latch;
int iterations = 10;
public LatchTask(int iterations, CountDownLatch latch) {
this.iterations = iterations;
this.latch = latch;
}
#Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < iterations; i++) {
System.out.println(threadName + " : " + i);
MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
}
System.out.println(threadName + " : Completed Task");
// countDown() « Decrements the count of the latch group.
if(latch != null)
latch.countDown();
}
}
CyclicBarriers A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
CyclicBarrier barrier = new CyclicBarrier(3);
barrier.await();
For example refer this Concurrent_ParallelNotifyies class.
Executer framework: we can use ExecutorService to create a thread pool, and tracks the progress of the asynchronous tasks with Future.
submit(Runnable), submit(Callable) which return Future Object. By using future.get() function we can block the main thread till the working threads completes its work.
invokeAll(...) - returns a list of Future objects via which you can obtain the results of the executions of each Callable.
Find example of using Interfaces Runnable, Callable with Executor framework.
#See also
Find out thread is still alive?
Apart from Thread.join() suggested by others, java 5 introduced the executor framework. There you don't work with Thread objects. Instead, you submit your Callable or Runnable objects to an executor. There's a special executor that is meant to execute multiple tasks and return their results out of order. That's the ExecutorCompletionService:
ExecutorCompletionService executor;
for (..) {
executor.submit(Executors.callable(yourRunnable));
}
Then you can repeatedly call take() until there are no more Future<?> objects to return, which means all of them are completed.
Another thing that may be relevant, depending on your scenario is CyclicBarrier.
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
Another possibility is the CountDownLatch object, which is useful for simple situations : since you know in advance the number of threads, you initialize it with the relevant count, and pass the reference of the object to each thread.
Upon completion of its task, each thread calls CountDownLatch.countDown() which decrements the internal counter. The main thread, after starting all others, should do the CountDownLatch.await() blocking call. It will be released as soon as the internal counter has reached 0.
Pay attention that with this object, an InterruptedException can be thrown as well.
You do
for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
t.join()
After this for loop, you can be sure all threads have finished their jobs.
Store the Thread-objects into some collection (like a List or a Set), then loop through the collection once the threads are started and call join() on the Threads.
You can use Threadf#join method for this purpose.
Although not relevant to OP's problem, if you are interested in synchronization (more precisely, a rendez-vous) with exactly one thread, you may use an Exchanger
In my case, I needed to pause the parent thread until the child thread did something, e.g. completed its initialization. A CountDownLatch also works well.
I created a small helper method to wait for a few Threads to finish:
public static void waitForThreadsToFinish(Thread... threads) {
try {
for (Thread thread : threads) {
thread.join();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
An executor service can be used to manage multiple threads including status and completion. See http://programmingexamples.wikidot.com/executorservice
try this, will work.
Thread[] threads = new Thread[10];
List<Thread> allThreads = new ArrayList<Thread>();
for(Thread thread : threads){
if(null != thread){
if(thread.isAlive()){
allThreads.add(thread);
}
}
}
while(!allThreads.isEmpty()){
Iterator<Thread> ite = allThreads.iterator();
while(ite.hasNext()){
Thread thread = ite.next();
if(!thread.isAlive()){
ite.remove();
}
}
}
I had a similar problem and ended up using Java 8 parallelStream.
requestList.parallelStream().forEach(req -> makeRequest(req));
It's super simple and readable.
Behind the scenes it is using default JVM’s fork join pool which means that it will wait for all the threads to finish before continuing. For my case it was a neat solution, because it was the only parallelStream in my application. If you have more than one parallelStream running simultaneously, please read the link below.
More information about parallel streams here.
The existing answers said could join() each thread.
But there are several ways to get the thread array / list:
Add the Thread into a list on creation.
Use ThreadGroup to manage the threads.
Following code will use the ThreadGruop approach. It create a group first, then when create each thread specify the group in constructor, later could get the thread array via ThreadGroup.enumerate()
Code
SyncBlockLearn.java
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* synchronized block - learn,
*
* #author eric
* #date Apr 20, 2015 1:37:11 PM
*/
public class SyncBlockLearn {
private static final int TD_COUNT = 5; // thread count
private static final int ROUND_PER_THREAD = 100; // round for each thread,
private static final long INC_DELAY = 10; // delay of each increase,
// sync block test,
#Test
public void syncBlockTest() throws InterruptedException {
Counter ct = new Counter();
ThreadGroup tg = new ThreadGroup("runner");
for (int i = 0; i < TD_COUNT; i++) {
new Thread(tg, ct, "t-" + i).start();
}
Thread[] tArr = new Thread[TD_COUNT];
tg.enumerate(tArr); // get threads,
// wait all runner to finish,
for (Thread t : tArr) {
t.join();
}
System.out.printf("\nfinal count: %d\n", ct.getCount());
Assert.assertEquals(ct.getCount(), TD_COUNT * ROUND_PER_THREAD);
}
static class Counter implements Runnable {
private final Object lkOn = new Object(); // the object to lock on,
private int count = 0;
#Override
public void run() {
System.out.printf("[%s] begin\n", Thread.currentThread().getName());
for (int i = 0; i < ROUND_PER_THREAD; i++) {
synchronized (lkOn) {
System.out.printf("[%s] [%d] inc to: %d\n", Thread.currentThread().getName(), i, ++count);
}
try {
Thread.sleep(INC_DELAY); // wait a while,
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("[%s] end\n", Thread.currentThread().getName());
}
public int getCount() {
return count;
}
}
}
The main thread will wait for all threads in the group to finish.
I had similar situation , where i had to wait till all child threads complete its execution then only i could get the status result for each of them .. hence i needed to wait till all child thread completed.
below is my code where i did multi-threading using
public static void main(String[] args) {
List<RunnerPojo> testList = ExcelObject.getTestStepsList();//.parallelStream().collect(Collectors.toList());
int threadCount = ConfigFileReader.getInstance().readConfig().getParallelThreadCount();
System.out.println("Thread count is : ========= " + threadCount); // 5
ExecutorService threadExecutor = new DriverScript().threadExecutor(testList, threadCount);
boolean isProcessCompleted = waitUntilCondition(() -> threadExecutor.isTerminated()); // Here i used waitUntil condition
if (isProcessCompleted) {
testList.forEach(x -> {
System.out.println("Test Name: " + x.getTestCaseId());
System.out.println("Test Status : " + x.getStatus());
System.out.println("======= Test Steps ===== ");
x.getTestStepsList().forEach(y -> {
System.out.println("Step Name: " + y.getDescription());
System.out.println("Test caseId : " + y.getTestCaseId());
System.out.println("Step Status: " + y.getResult());
System.out.println("\n ============ ==========");
});
});
}
Below method is for distribution of list with parallel proccessing
// This method will split my list and run in a parallel process with mutliple threads
private ExecutorService threadExecutor(List<RunnerPojo> testList, int threadSize) {
ExecutorService exec = Executors.newFixedThreadPool(threadSize);
testList.forEach(tests -> {
exec.submit(() -> {
driverScript(tests);
});
});
exec.shutdown();
return exec;
}
This is my wait until method: here you can wait till your condition satisfies within do while loop . in my case i waited for some max timeout .
this will keep checking until your threadExecutor.isTerminated() is true with polling period of 5 sec.
static boolean waitUntilCondition(Supplier<Boolean> function) {
Double timer = 0.0;
Double maxTimeOut = 20.0;
boolean isFound;
do {
isFound = function.get();
if (isFound) {
break;
} else {
try {
Thread.sleep(5000); // Sleeping for 5 sec (main thread will sleep for 5 sec)
} catch (InterruptedException e) {
e.printStackTrace();
}
timer++;
System.out.println("Waiting for condition to be true .. waited .." + timer * 5 + " sec.");
}
} while (timer < maxTimeOut + 1.0);
return isFound;
}
Use this in your main thread: while(!executor.isTerminated());
Put this line of code after starting all the threads from executor service. This will only start the main thread after all the threads started by executors are finished. Make sure to call executor.shutdown(); before the above loop.
Related
Why Set.add() method does not work in anonymous Runnable?
I would like to run 20 threads simultaneously to test my id generator. However, uniqueSet.add(id) is not adding id to the set. When I assert, it says set size is zero. #Test void should_generate_unique_id_concurrently() throws InterruptedException { Set<Long> uniqueSet = ConcurrentHashMap.newKeySet(); final int numberOfThreads = 20; ExecutorService service = Executors.newFixedThreadPool(numberOfThreads); CountDownLatch latch = new CountDownLatch(numberOfThreads); for (int i = 0; i < numberOfThreads; i++) { service.submit(() -> { try { latch.countDown(); latch.await(); long id = idGenerator.nextId(); uniqueSet.add(id); } catch (InterruptedException e) { e.printStackTrace(); } }); } assertEquals(numberOfThreads, uniqueSet.size()); }
The uniqueSet.add(id) probably is working just fine. But most likely, none of those tasks is able to execute that line before the main thread asks for the size of the set. Each of your task calls latch.countDown() before it does anything else. That means, none of the tasks will be able to do anything else until all twenty of them have been started. Meanwhile, your main thread asks for the size of the set immediately after it submits the last task to the thread pool. The main thread already is running at that point. Probably most of the pool threads are sleeping in latch.await() The ones that aren't haven't even got that far yet. The main thread probably always calls uniqueSet.size() before any of the worker threads reaches the uniqueSet.add(id) line. #VGR suggested a good solution to your problem: After your main thread has submitted the twenty tasks, and before it checks the size of the set, it could shut the thread pool down: for (int i = 0; i < numberOfThreads; i++) { service.submit(...); } // Tell the `service` to refuse new tasks, and to shut down // _after_ all of the pending tasks have completed. service.shutdown(); // Wait until all of the tasks have completed. service.awaitTermination(); assertEquals(numberOfThreads, uniqueSet.size());
java multiple threads running , stop threads when one thread finds solution
I'm having troubles trying to stop my program that has multiple threads running, all threads running are trying to find the same solution but once one thread finds the solution all other threads are to stop. In the main method I have created a thread group and add threads to it using a for loop and start them ThreadGroup tg = new ThreadGroup("thread group"); Thread th; for(int i = 0; i<4; i++){ th = new Thread(tg, new Runnable(), "Thread " + i) th.start(); } in the class that implements Runnable I am having troubles trying to figure out how to make it so that once one of the thread finds a solution all the threads will stop. What ends up happening is that either the other threads keep running and sometimes the threads will interupt each other and write over each other.
You have to interrupt those thread (and handle interruption in the runnable). I also not sure if you should use ThreadGroup - I remember seeing a Sonar warning about them. You would perhaps better have to an ExecutorService and do that using a CountDownLatch (that's one way to do that): ExecutorService es = Executors.newFixedThreadPool(100); CountDownLatch cdl = new CountDownLatch(1); for (int i = 0; i < 100; ++i) { es.submit(() -> { Thread.sleep(TimeUnit.SECONDS.toMillis(30)); // + exception handling cdl.countDown(); }); } cdl.await(); // or await(5, TimeUnit.MINUTES); es.shutdownNow(); The trick is: You create an ExecutorService with a pool of 100 threads. You create a CoundDownLatch - a barrier - with a count of 1. You submit your task which, when their job is done, invoke cdl.countDown(); reducing the counter from 1 to 0. The parent thread wait for the CountDownLatch to reduce to 0 - you should probably use the second version (to block until 5 minutes for example). If all Runnable fails, you won't have a result: either use a maximum await time, either you could add another CountDownLatch, this time with a count of 100 (the number of threads), countDown() in a try/finally, and in another thread, interrupt the one awaiting on the cdl. You could also do that in a loop: CountDownLatch allCdl = new CountDownLatch(100); for (;allCdl.getCount() != 0;) { if (!cdl.await(60, TimeUnit.SECONDS)) { if (allCdl.getCount() == 0) { break; } } } However, the javadoc of getCount() mention that This method is typically used for debugging and testing purposes. (see CyclicBarrier). Not sure if this is the correct usage.
Upon realizing that a solution has been found, the victorious thread should signal the parent – which then signals all other children to stop, or simply kills them.
ThreadGroup tg = new ThreadGroup("thread group"); CountDownLatch latch = new CountDownLatch(1); AtomicInteger result = new AtomicInteger(); Random random = new Random(); for (int i = 0; i < 4; i++) { Thread th = new Thread(tg, () -> { try { Thread.sleep(random.nextInt(10000)); result.set(42); latch.countDown(); System.out.println(Thread.currentThread().getName() + " completed task first"); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " was interrupted before it could finish the task"); } }, "Thread " + i); th.start(); } while (latch.getCount() > 0) { try { latch.await(); } catch (InterruptedException ignored) { } } tg.interrupt(); System.out.println("The result is " + result.get()); This example shows how to wait until a thread finishes. You need to make sure your action is interruptible. Thread.sleep as shown in this example is interrubtible by default. See oracle docs for more info. Also note that it is impossible to guarantee that all other threads will be interrupted before they complete. If you need to make sure to handle only one result, synchronize the access to your result variable and discard any changes beyond the first.
Do I need to call join() when stopping a Thread in Java?
I have these 5 simple thread that run a while loop: flasherThread = new Thread(new Runnable() { #Override public void run() { while(running.get()) { // do network stuff } } }); running is declared as private final AtomicBoolean running;. I have this method: public void stopFlasherThread() { running.set(false); } My question is by setting the flag to false that stops the thread immediately ? Or do I need to call flasherThread.join() to make sure that the thread has stopped ? The main issue is that I have 4-5 of these at a time. So I have a loop such as: for (int i = 0; i < 5; i++) { ThreadArrayList.get(i).stopFlasherThread(); ThreadArrayList.get(i).join() // should I do this ? } Any help would be great! Thanks
According to the official documentation on join: The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, t.join(); causes the current thread to pause execution until t's thread terminates. So, no... or not necessarily, only if you need the result of the work of that thread to do something. The join will not stop / interrupt the thread, it will wait for it to finish its work. The stopFlasherThread will make the loop stop. I would advise you to follow a different approach on using threads on Java using ExecutorService. For example: ExecutorService executor = Executors.newSingleThreadExecutor(); Future<AtomicInteger> futureResult = executor.submit(new Callable<AtomicInteger>() { #Override public AtomicInteger call() { // Here I return a random integer, but you can do your proper calculation AtomicInteger atomicInteger = new AtomicInteger(ThreadLocalRandom.current().nextInt()); System.out.println(Thread.currentThread().getName() + " " + atomicInteger); return atomicInteger; } }); // Thread returns result, but continues to execute as it is a single thread pool try { System.out.println(Thread.currentThread().getName() + " " + futureResult.get()); } catch (InterruptedException e) { // Handle exception properly e.printStackTrace(); } catch (ExecutionException e) { // Handle exception properly e.printStackTrace(); } // Stop all threads executor.shutdownNow(); There I define an inline class that extends the Callable interface and implement the call method to perform a task in another thread. This returns the result of the computation in the variable futureResult which is a Future. Since executor is a thread pool, it continues to be available to take tasks even though our task here has already been resolved. To finish the whole thread pool loop you can do a executor.shutdownNow().
How to make thread work in order and run many times? [duplicate]
This question already has answers here: Execution order of multiple threads (4 answers) Closed 6 years ago. I have 3 thread which i would like it to print in order but when I run the program it's keep getting result . I don't understand how it couldn't run thread in order. I would like to continue run thread 1 and 2 and 3 respectively. In each thread there is a loop for printing it's multiple times. So I would like to make the main thread to run each thread in order. This is my code. threadMessage("Starting MessageLoop thread"); long patience = long startTime = System.currentTimeMillis(); Thread t = new Thread(new MessageLoop()); Thread t2 = new Thread(new MessageLoop2()); Thread t3 = new Thread(new MessageLoop3()); t.setPriority(10); t2.setPriority(5); t3.setPriority(1); t.start(); t2.start(); t3.start(); This is my thread function(3 threads) private static class MessageLoop implements Runnable { public void run() { try { for(int i = 0;i<20;i++) { Thread.sleep(1000); // Print a message threadMessage("A"); } } catch (InterruptedException e) { threadMessage("thread interrupted"); } } } private static class MessageLoop2 implements Runnable { public void run() { try { for(int i = 0;i<20;i++) { Thread.sleep(1000); // Print a message threadMessage("B"); } } catch (InterruptedException e) { threadMessage("thread interrupted"); } } private static class MessageLoop3 implements Runnable { public void run() { String importantInfo = "E"; try { for(int i = 0;i<20;i++) { Thread.sleep(1000); // Print a message threadMessage(importantInfo); } } catch (InterruptedException e) { threadMessage("Thread interrupted"); } } And this is my code to make it run in order. I want to make my program run in order like this MessageLoop1 and 2 and 3 respectively. while (t.isAlive()) { threadMessage("Still waiting..."); t.join(2000); if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { threadMessage("Tired of waiting!"); t.interrupt(); // Shouldn't be long now // -- wait indefinitely t.join(); } while(t2.isAlive()){ threadMessage("Still waiting..."); t2.join(1000); if (((System.currentTimeMillis() - startTime) > patience) && t2.isAlive()) { threadMessage("Tired of waiting!"); t2.interrupt(); // Shouldn't be long now // -- wait indefinitely t2.join(); } } while(t3.isAlive()){ threadMessage("Still waiting..."); t3.join(1000); if (((System.currentTimeMillis() - startTime) > patience) && t3.isAlive()) { threadMessage("Tired of waiting!"); t3.interrupt(); // Shouldn't be long now // -- wait indefinitely t3.join(); } } } But the result is coming like B,A,C. Can anyone explain this situation? And are my code wrong? Thank you!
That's how threads work. You don't get a guarantee at all which thread will finish first - and that's by design. I assume what you want, is actually what the jdk calls a future and an ExecutorService. (pseudocode - will have syntax errors) ExecutorService s = Executors.newCachedThreadPool(); try { Future f1 = s.submit(new MessageLoop()); Future f2 = s.submit(new MessageLoop2()); Future f3 = s.submit(new MessageLoop3()); f1.await(10, TimeUnit.SECONDS); // waits for the first thread to finish // first thread finished now f2.await(10, TimeUnit.SECONDS); // second thread finished now // ... } finally { s.shutdown(); } very important is to manage the proper shutdown of the ExecutorService, as the executor service will manage a couple of threads that run until you terminate them. if you don't shut it down, then your applicationo will not terminate.
What makes you assume you are controlling order? The individual MessageLoop implementations are not blocked from executing in any way. So they just will run at the descretion of the thread scheduling. You would need to introduce a shared ressource that takes the role of lock between the control thread (trying to enforce the order) and the worker threads. In your current code the control thread just applies a special sequence on collecting the termination of the workers. That may have been executed and completed earlier in time. If you are interested in a sequential execution and do not want to execute the tasks inline (same thread as your control), then you might just execute the threads in sequence to achieve your goal of sequential execution. (start each thread and wait for termination before starting another). As you seam to have a restriction on the order of execution you would need some semaphore to coordinate such execution.
Java ExecutorService: awaitTermination of all recursively created tasks
I use an ExecutorService to execute a task. This task can recursively create other tasks which are submitted to the same ExecutorService and those child tasks can do that, too. I now have the problem that I want to wait until all the tasks are done (that is, all tasks are finished and they did not submit new ones) before I continue. I cannot call ExecutorService.shutdown() in the main thread because this prevents new tasks from being accepted by the ExecutorService. And Calling ExecutorService.awaitTermination() seems to do nothing if shutdown hasn't been called. So I am kinda stuck here. It can't be that hard for the ExecutorService to see that all workers are idle, can it? The only inelegant solution I could come up with is to directly use a ThreadPoolExecutor and query its getPoolSize() every once in a while. Is there really no better way do do that?
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 arrives == registers. Since prior to each recursive call invokes register a phase increment will happen when all invocations are complete.
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.
Wow, you guys are quick:) Thank you for all the suggestions. Futures don't easily integrate with my model because I don't know how many runnables are scheduled beforehand. So if I keep a parent task alive just to wait for it's recursive child tasks to finish I have a lot of garbage laying around. I solved my problem using the AtomicInteger suggestion. Essentially, I subclassed ThreadPoolExecutor and increment the counter on calls to execute() and decrement on calls to afterExecute(). When the counter gets 0 I call shutdown(). This seems to work for my problems, not sure if that's a generally good way to do that. Especially, I assume that you only use execute() to add Runnables. As a side node: I first tried to check in afterExecute() the number of Runnables in the queue and the number of workers that are active and shutdown when those are 0; but that didn't work because not all Runnables showed up in the queue and the getActiveCount() didn't do what I expected either. Anyhow, here's my solution: (if anybody finds serious problems with this, please let me know:) public class MyThreadPoolExecutor extends ThreadPoolExecutor { private final AtomicInteger executing = new AtomicInteger(0); public MyThreadPoolExecutor(int coorPoolSize, int maxPoolSize, long keepAliveTime, TimeUnit seconds, BlockingQueue<Runnable> queue) { super(coorPoolSize, maxPoolSize, keepAliveTime, seconds, queue); } #Override public void execute(Runnable command) { //intercepting beforeExecute is too late! //execute() is called in the parent thread before it terminates executing.incrementAndGet(); super.execute(command); } #Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); int count = executing.decrementAndGet(); if(count == 0) { this.shutdown(); } } }
You could create your own thread pool which extends ThreadPoolExecutor. You want to know when a task has been submitted and when it completes. public class MyThreadPoolExecutor extends ThreadPoolExecutor { private int counter = 0; public MyThreadPoolExecutor() { super(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } #Override public synchronized void execute(Runnable command) { counter++; super.execute(command); } #Override protected synchronized void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); counter--; notifyAll(); } public synchronized void waitForExecuted() throws InterruptedException { while (counter == 0) wait(); } }
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.
(mea culpa: its a 'bit' past my bedtime ;) but here's a first attempt at a dynamic latch): package oss.alphazero.sto4958330; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; public class DynamicCountDownLatch { #SuppressWarnings("serial") private static final class Sync extends AbstractQueuedSynchronizer { private final CountDownLatch toplatch; public Sync() { setState(0); this.toplatch = new CountDownLatch(1); } #Override protected int tryAcquireShared(int acquires){ try { toplatch.await(); } catch (InterruptedException e) { throw new RuntimeException("Interrupted", e); } return getState() == 0 ? 1 : -1; } public boolean tryReleaseShared(int releases) { for (;;) { int c = getState(); if (c == 0) return false; int nextc = c-1; if (compareAndSetState(c, nextc)) return nextc == 0; } } public boolean tryExtendState(int acquires) { for (;;) { int s = getState(); int exts = s+1; if (compareAndSetState(s, exts)) { toplatch.countDown(); return exts > 0; } } } } private final Sync sync; public DynamicCountDownLatch(){ this.sync = new Sync(); } public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); } public void countDown() { sync.releaseShared(1); } public void join() { sync.tryExtendState(1); } } This latch introduces a new method join() to the existing (cloned) CountDownLatch API, which is used by tasks to signal their entry into the larger task group. The latch is pass around from parent Task to child Task. Each task would, per Suraj's pattern, first 'join()' the latch, do its task(), and then countDown(). To address situations where the main thread launches the task group and then immediately awaits() -- before any of the task threads have had a chance to even join() -- the topLatch is used int inner Sync class. This is a latch that will get counted down on each join(); only the first countdown is of course significant, as all subsequent ones are nops. The initial implementation above does introduce a semantic wrinkle of sorts since the tryAcquiredShared(int) is not supposed to be throwing an InterruptedException but then we do need to deal with the interrupt on the wait on the topLatch. Is this an improvement over OP's own solution using Atomic counters? I would say probably not IFF he is insistent upon using Executors, but it is, I believe, an equally valid alternative approach using the AQS in that case, and, is usable with generic threads as well. Crit away fellow hackers.
If you want to use JSR166y classes - e.g. Phaser or Fork/Join - either of which might work for you, you can always download the Java 6 backport of them from: http://gee.cs.oswego.edu/dl/concurrency-interest/ and use that as a basis rather than writing a completely homebrew solution. Then when 7 comes out you can just drop the dependency on the backport and change a few package names. (Full disclosure: We've been using the LinkedTransferQueue in prod for a while now. No issues)
I must say, that solutions described above of problem with recursive calling task and wait for end suborder tasks doesn't satisfy me. There is my solution inspired by original documentation from Oracle there: CountDownLatch and example there: Human resources CountDownLatch. The first common thread in process in instance of class HRManagerCompact has waiting latch for two daughter's threads, wich has waiting latches for their subsequent 2 daughter's threads... etc. Of course, latch can be set on the different value than 2 (in constructor of CountDownLatch), as well as the number of runnable objects can be established in iteration i.e. ArrayList, but it must correspond (number of count downs must be equal the parameter in CountDownLatch constructor). Be careful, the number of latches increases exponentially according restriction condition: 'level.get() < 2', as well as the number of objects. 1, 2, 4, 8, 16... and latches 0, 1, 2, 4... As you can see, for four levels (level.get() < 4) there will be 15 waiting threads and 7 latches in the time, when peak 16 threads are running. package processes.countdownlatch.hr; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** Recursively latching running classes to wait for the peak threads * * #author hariprasad */ public class HRManagerCompact extends Thread { final int N = 2; // number of daughter's tasks for latch CountDownLatch countDownLatch; CountDownLatch originCountDownLatch; AtomicInteger level = new AtomicInteger(0); AtomicLong order = new AtomicLong(0); // id latched thread waiting for HRManagerCompact techLead1 = null; HRManagerCompact techLead2 = null; HRManagerCompact techLead3 = null; // constructor public HRManagerCompact(CountDownLatch countDownLatch, String name, AtomicInteger level, AtomicLong order){ super(name); this.originCountDownLatch=countDownLatch; this.level = level; this.order = order; } private void doIt() { countDownLatch = new CountDownLatch(N); AtomicInteger leveli = new AtomicInteger(level.get() + 1); AtomicLong orderi = new AtomicLong(Thread.currentThread().getId()); techLead1 = new HRManagerCompact(countDownLatch, "first", leveli, orderi); techLead2 = new HRManagerCompact(countDownLatch, "second", leveli, orderi); //techLead3 = new HRManagerCompact(countDownLatch, "third", leveli); techLead1.start(); techLead2.start(); //techLead3.start(); try { synchronized (Thread.currentThread()) { // to prevent print and latch in the same thread System.out.println("*** HR Manager waiting for recruitment to complete... " + level + ", " + order + ", " + orderi); countDownLatch.await(); // wait actual thread } System.out.println("*** Distribute Offer Letter, it means finished. " + level + ", " + order + ", " + orderi); } catch (InterruptedException e) { e.printStackTrace(); } } #Override public void run() { try { System.out.println(Thread.currentThread().getName() + ": working... " + level + ", " + order + ", " + Thread.currentThread().getId()); Thread.sleep(10*level.intValue()); if (level.get() < 2) doIt(); Thread.yield(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /*catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ // TODO Auto-generated method stub System.out.println("--- " +Thread.currentThread().getName() + ": recruted " + level + ", " + order + ", " + Thread.currentThread().getId()); originCountDownLatch.countDown(); // count down } public static void main(String args[]){ AtomicInteger levelzero = new AtomicInteger(0); HRManagerCompact hr = new HRManagerCompact(null, "zero", levelzero, new AtomicLong(levelzero.longValue())); hr.doIt(); } } Possible commented output (with some probability): first: working... 1, 1, 10 // thread 1, first daughter's task (10) second: working... 1, 1, 11 // thread 1, second daughter's task (11) first: working... 2, 10, 12 // thread 10, first daughter's task (12) first: working... 2, 11, 14 // thread 11, first daughter's task (14) second: working... 2, 11, 15 // thread 11, second daughter's task (15) second: working... 2, 10, 13 // thread 10, second daughter's task (13) --- first: recruted 2, 10, 12 // finished 12 --- first: recruted 2, 11, 14 // finished 14 --- second: recruted 2, 10, 13 // finished 13 (now can be opened latch 10) --- second: recruted 2, 11, 15 // finished 15 (now can be opened latch 11) *** HR Manager waiting for recruitment to complete... 0, 0, 1 *** HR Manager waiting for recruitment to complete... 1, 1, 10 *** Distribute Offer Letter, it means finished. 1, 1, 10 // latch on 10 opened --- first: recruted 1, 1, 10 // finished 10 *** HR Manager waiting for recruitment to complete... 1, 1, 11 *** Distribute Offer Letter, it means finished. 1, 1, 11 // latch on 11 opened --- second: recruted 1, 1, 11 // finished 11 (now can be opened latch 1) *** Distribute Offer Letter, it means finished. 0, 0, 1 // latch on 1 opened
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.
The only inelegant solution I could come up with is to directly use a ThreadPoolExecutor and query its getPoolSize() every once in a while. Is there really no better way do do that? You have to use shutdown() ,awaitTermination()and shutdownNow() methods in a proper sequence. shutdown(): Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. awaitTermination():Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. shutdownNow(): Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. Recommended way from oracle documentation page of ExecutorService: void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(60, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(60, TimeUnit.SECONDS)) System.err.println("Pool did not terminate"); } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } You can replace if condition with while condition in case of long duration in completion of tasks as below: Change if (!pool.awaitTermination(60, TimeUnit.SECONDS)) To while(!pool.awaitTermination(60, TimeUnit.SECONDS)) { Thread.sleep(60000); } You can refer to other alternatives (except join(), which can be used with standalone thread ) in : wait until all threads finish their work in java
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'