Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A CountDownLatch's latch.await() method vs Thread.join()

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
like image 836
Ivan Avatar asked Sep 29 '10 14:09

Ivan


1 Answers

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.

like image 108
John Vint Avatar answered Sep 17 '22 23:09

John Vint