Real Life Examples For CountDownLatch and CyclicBarrier

Sunny Gupta picture Sunny Gupta · Apr 14, 2012 · Viewed 21.6k times · Source

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.

Answer

Shailesh kumar picture Shailesh kumar · Sep 5, 2015

In a hypothetical theater:

  • It is called Mutex if only one person is allowed to watch the play.
  • It is called Semaphore if N number of people are allowed to watch the play. If anybody leaves the Theater during the play then other person can be allowed to watch the play.
  • It is called CountDownLatch if no one is allowed to enter until every person vacates the theater. Here each person has free will to leave the theater.
  • It is called CyclicBarrier if the play will not start until every person enters the theater. Here a showman can not start the show until all the persons enter and grab the seat. Once the play is finished the same barrier will be applied for next show.

Here, a person is a thread, a play is a resource.