What is the difference between join and CountDownLatch?

Adam Lee picture Adam Lee · Sep 4, 2012 · Viewed 9k times · Source

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?

Answer

Jeffrey picture Jeffrey · Sep 4, 2012

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();