Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between join and CountDownLatch?

When waiting for other threads to finish, we can use either join or CountdownLatch. What are the pros and cons of using either of those two mechanisms?

like image 975
Adam Lee Avatar asked Sep 03 '12 22:09

Adam Lee


People also ask

What is CountDownLatch used for?

CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.

What is the difference between a CountDownLatch and a CyclicBarrier?

As stated in the definitions, CyclicBarrier allows a number of threads to wait on each other, whereas CountDownLatch allows one or more threads to wait for a number of tasks to complete. In short, CyclicBarrier maintains a count of threads whereas CountDownLatch maintains a count of tasks.

What the difference between join and wait?

wait() method is primarily used for the inter-thread communication. On the other hand join() is used for adding sequencing between multiple threads, one thread starts execution after first thread execution finished.

What is the difference between join and sleep?

There is a difference between join() and sleep(). join() will wait until the timeout expires or the thread finishes. sleep() will just wait for the specified amount of time unless interrupted. So it is perfectly possible for join() to return much faster than the specified time.


1 Answers

You can only use Thread.join if you're handling the threads yourself. Most people choose not to deal with the minutia of thread handling directly, and instead use an ExecutorService to handle it for them. ExecutorServices do not directly reveal how they are executing tasks, so you would have to use a CountDownLatch: (Assuming you don't want to just shutdown the whole service, that is.)

ExecutorService service = Executors.newFixedThreadPool(5); final CountDownLatch latch = new CountDownLatch(5);  for(int x = 0; x < 5; x++) {     service.submit(new Runnable() {         public void run() {             // do something             latch.countDown();         }     }); }  latch.await(); 
like image 197
Jeffrey Avatar answered Sep 24 '22 07:09

Jeffrey