Concurrency in non-trivial systems is difficult. java.util.concurrent. CountDownLatch
is one of my favourite concurrent core Java classes, because it simplifies the synchronization of threads. This class is useful when you want to wait until some task in another thread completes, before continuing in the current thread.
CountDownLatch causes one or more dependent threads to wait until tasks in one or more task threads completes.
- CountDownLatch is
constructed
with a count (x) - Dependent Threads wait by calling
CountDownLatch::await
CountDownLatch::countDown
must be called (x) times by Task Threads, causingCountDownLatch::await
calls in Dependent Threads to be released
In the following example, the Application main thread needs to wait for the DatabaseService thread to complete initialisation, before the Application can complete its own initialisation.
Click on the flashing arrow, to take 10 steps through Codelytics’ visualization of CountDownLatch.
Step through CountDownLatch:
Http iframes are not shown in https pages in many major browsers. Please read this post for details.In the old days, before Java 1.5, we used to used Object::wait
and Object::notify
, to achieve this form of synchronization. Nowadays, using CountDownLatch is easier.
For more information see:
Do you like this Codelytics’ visualization?
If you like our visualizations, be sure to subscribe to our mailing list below. With your free subscription, we will periodically send you alerts about new tutorials and visualizations posted here.
What do you think about CountDownLatch? What do you think about this Codelytics’ visualization? We’d love to see your feedback in the comments below.
Image source: Greg Neate, image modified
Leave a Reply