views:

69

answers:

3

I saw a stackoverflow member suggest using Thread.join() to have a "main" thread wait for 2 "task" threads to complete.

I will frequently do something different (shown below) and I want to know if there are any problems with my approach.

final CountDownLatch latch = new CountDownLatch(myItems.length);

for (Item item : myItems) {  
  //doStuff launches a Thread that calls latch.countDown() as it's final act  
  item.doStuff(latch);   
}

latch.await();  //ignoring Exceptions for readability
+3  A: 

Your solution is easier to scale. Thread.join() was a perfectly fine way of resolving your issue before CountdownLatch and the other synchronizers were created.

In terms of readability, I would choose the CountdownLatch approach over joining on each thread. This also allows you to change the implementation of Item to maybe submit to an Executor service instead of using Threads directly.

John V.
A: 

The countdown latch is preferred for simultaneously starting all the threads at the same time.

Suresh S
+3  A: 

I would prefer using a Future (easy if you're using an ExecutorService). Then after submitting all the tasks wait for them all to finish.

 Collection<Future<Void>> futures = new ArrayList<Future<Void>>(myItems.length());
 for ( Runnable item : myItems ) {
     futures.add(executor.submit(item, null));

 for ( Future<Void> future : futures ) 
     future.get();  //easy to add a timeout here

The final for-loop could easily be separated into a utily method. This encapsulates the synchronization and makes it easy to add timeouts.

It's also more applicable to the general case, where the worker threads actually need to return a result. (If you don't care about what the worker threads end up doing, why do you need to wait for them?)

Mark Peters
I've always thought I should look into the Future class?/inteface?
Ivan