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?
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.
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.
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.
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.
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. ExecutorService
s 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With