Sunday 19 February 2012

Coordinating threads

In our multithreaded application we may need to coordinate the work of our threads. The most occurring situation is waiting for all the threads once they finish their work.

Let's take a simple example: we have 2 threads that are doing some mathematical operations and we need to wait for both of them before we proceed with further processing. We could do that using thread's join() method:

If the number of threads is higher, this implementation will look much more nastier, as we would need to invoke join() method on all of them.


That's why the better solution is to use CountDownLatch, "that allows one or more threads to wait until a set of operations being performed in other threads completes", as Javadoc says.

In the constructor of CountDownLatch we specify a count - as each of our threads will be doing only one countdown once work is finished, it is equal to the number of threads. await() method makes the current thread to stop, until latch has counted down to zero. It also provides possibility to wait for the specified time.

If threads must repeatedly count down in a similar way, we would need to use CyclicBarrier instead.  

No comments:

Post a Comment