What is the difference between CountDownLatch and CyclicBarrier, and when would you use each?
CountDownLatch is a one-shot, asymmetric coordination tool: some number of threads call countDown() to decrement a counter, while a possibly different set of threads call await() to block until that counter reaches zero. Once the count hits zero it stays at zero permanently -- a CountDownLatch cannot be reset or reused. It's well suited to situations like waiting for a fixed number of services to finish starting up, or waiting for a fixed number of independent parallel tasks to complete. CyclicBarrier, by contrast, is reusable and symmetric: all N participating threads call the same await() method, all of them block until the last one arrives, and then all of them are released together, optionally running a barrier action first. Because it automatically resets for the next round, it's well suited to multi-phase parallel computations where every thread must finish the current phase before any of them is allowed to begin the next one.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response