Real Life Examples For CountDownLatch and CyclicBarrier
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.
The key difference is that CountDownLatch
separates threads into waiters and arrivers while all threads using a CyclicBarrier
perform both roles.
- With a latch, the waiters wait for the last arriving thread to arrive, but those arriving threads don't do any waiting themselves.
- With a barrier, all threads arrive and then wait for the last to arrive.
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.