Example of deadlock

Tina and Maria are both nurse in a very small clinic.
Both of them share equipment in the clinic. There are only 3 limited equipment in the clinic.

  • Scissor
  • Bandage
  • Antiseptic

Today, 2 badly injured patient come in at the same time.

  • To treats a patient, they will first gather all the necessary equipment.
  • They need to gather all equipment within 30 secs or else the patient will die.

And so… the race begin.

Each Nurse class represent a separated thread.
– class constructor take in name of the nurse and the list of equipment needed.
– run() method is implemented to grab equipment until the list given is completely collected.
– stillAlive() method is something like timeout. If the nurse failed to complete the list in 30 sec. The thread will end.
– random interval is added to simulate the time to look for equipment.

Simulate the limited resources, only 1 nurse can get each equipment at a time. Nurse have to wait for others to release the equipment if the equipment is occupied.
– nurse can only take equipment that is unoccupied. (no owner)
– nurse will invoke lock() to try and get the equipment.
– release() method will be invoked after the list is completed so that other can get the equipment.

So, in this example both unlucky patient die after struggled for 30 sec.
Why? because dead lock happened. Tina is waiting for scissor but Maria got it.
Maria is waiting for bandage but Tina got it. And both of them not releasing the equipment.

Example output :
Note : The output might vary depends on the wait time.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">