javaconcurrencyconceptual

Real Life Examples For CountDownLatch and CyclicBarrier


One example is given by one of our trainers when he was explaining difference between CountDownLatch and CyclicBarrier.

CountDownLatch: Suppose a stone can be lifted by 10 people so you will wait for all 10 to come. Then only you can lift the stone.

CyclicBarrier: If you are going to a picnic, and you need to first meet at some common point from where you all will start your journey.

If Anybody agrees with these comments please give me some details.

I have already read the sun API for both these classes. But I need some more explaination.


Solution

  • The key difference is that CountDownLatch separates threads into waiters and arrivers while all threads using a CyclicBarrier perform both roles.

    Your latch example implies that all ten people must wait to lift the stone together. This is not the case. A better real world example would be an exam prompter who waits patiently for each student to hand in their test. Students don't wait once they complete their exams and are free to leave. Once the last student hands in the exam (or the time limit expires), the prompter stops waiting and leaves with the tests.