concept deadlock in category software development

appears as: deadlocks, deadlock, A deadlock, deadlock
Seriously Good Software: Code that works, survives, and wins

This is an excerpt from Manning's book Seriously Good Software: Code that works, survives, and wins.

It’s quite clear from the policy specification that groups are the synchronization units of our class. In practice, connectTo should acquire the monitors of the two groups being merged. Anytime a method needs more than one monitor, the risk of a deadlock arises. A deadlock is a condition where two or more threads are stuck, each one waiting for a monitor that another one holds. They’re waiting for each other in a cyclic pattern, forever.

The simplest deadlock scenario occurs when thread 1 attempts to acquire monitor A and then monitor B, whereas thread 2 requests them in the opposite order. An unlucky scheduling may cause thread 1 to successfully acquire A and then thread 2 to successfully acquire B before thread 1 does. At that point, the threads are stuck in a deadlock. This scenario can easily play out with the following natural but faulty implementation of connectTo:

   public void connectTo(Container other) {
      synchronized (group) {
         synchronized (other.group) {
            ...   #1 The actual operation here
         }
      }
   }


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":3,\"ch\":18},{\"line\":3,\"ch\":20}]]"}
!@%STYLE%@!

If one thread invokes a.connectTo(b) and another thread simultaneously invokesb.connectTo(a), they risk the textbook case of deadlock. Generally speaking, you have two ways to avoid such deadlocks without restricting the class clients in any way: atomic lock sequences or ordered lock sequences.