Monday, March 14, 2016

CyclicBarrier Example

CyclicBarrier is a very interesting functionality for Concurrency in Java. Here is a quick example which shows how this is implemented

1. Imagine a scenario where two doctors are needed to see a patient. One doctor has to wait while the other gets available.
2. So a doctor waits at a "Barrier" for the second doctor to come and only then do both proceed with the patient
3. And this need to be Cyclic in nature for all the patients in the hospital, i.e the Barrier needs to be Cyclic in nature
4. This is a simple example which showcases the "Cyclic" nature of the CyclicBarrier. For a detailed demo, you can refer to this page



Output

Doctor Thread-1 : READY to see the Patient -BatMan
Doctor Thread-2 : READY to see the Patient -BatMan
Doctor Thread-2 : WORKING on Patient-BatMan since the team is here
Doctor Thread-1 : WORKING on Patient-BatMan since the team is here
Doctor Thread-2 : DONE with the Patient -BatMan
Doctor Thread-2 : READY to see the Patient -SuperMan
Doctor Thread-1 : DONE with the Patient -BatMan
Doctor Thread-1 : READY to see the Patient -SuperMan
Doctor Thread-1 : WORKING on Patient-SuperMan since the team is here
Doctor Thread-2 : WORKING on Patient-SuperMan since the team is here
Doctor Thread-2 : DONE with the Patient -SuperMan
Doctor Thread-2 : READY to see the Patient -IronMan
Doctor Thread-1 : DONE with the Patient -SuperMan
Doctor Thread-1 : READY to see the Patient -IronMan
Doctor Thread-1 : WORKING on Patient-IronMan since the team is here
Doctor Thread-2 : WORKING on Patient-IronMan since the team is here
Doctor Thread-1 : DONE with the Patient -IronMan
Doctor Thread-2 : DONE with the Patient -IronMan

No comments:

Post a Comment