javamultithreadingreentrancy

Re-entrancy in Java saves us from a deadlock situation in this code sample.. How, why?


I'm new to Java and OOP. I'm reading concurrency in java and in chapter 2, it talks about re-entrancy. I don't quite understand how a deadlock situation would occur. Can some one break this situation down for me to understand the details line by line?

Thank you in advance.

If intrinsic locks were not reentrant, the call to super.doSomething would never be able to acquire the lock because it would be considered already held, and the thread would permanently stall waiting for a lock it can never acquire.

public class Widget {
    public synchronized void doSomething() {
      ...
    }
}
public class LoggingWidget extends Widget {
   public synchronized void doSomething() {
      System.out.println(toString() + ": calling doSomething");
      super.doSomething();
   }
}

and the thread would permanently stall waiting for a lock it can never acquire.

How, why, which thread?


Solution

  • How, why, which thread?

    The thread that deadlocks is the thread that attempts to acquire the lock; i.e. this one.


    How:

    1. Obtain reference to a LoggingWidget instance

    2. Call doSomething() on the instance

    3. The call to LoggingWidget.doSomething() acquires the lock on the instance, since the method is synchronized.

    4. The called method then calls super.doSomething().

    5. The call to Widget.doSomething() tries to acquire the lock on the instance (again!), since the supertype method is also synchronized.

    At step #5. the current thread attempts to acquire a primitive lock on an instance that it has already locked. If primitive locks were not reentrant, then that would deadlock ...

    But fortunately, there is no deadlock in reality. The fact that primitive locks are reentrant means that step #5 doesn't need to acquire the lock (it already has it), and the whole waiting-for-myself-to-do-something-that-cannot-happen scenario simply does not arise.


    Why: By the inescapable power of Murphy's Law. "If anything can go wrong, it will." :-)

    Which thread: According to Finagle's Law, it will be the one that causes the most damage. :-)

    These so-called "laws" have not been demonstrated scientifically. But that doesn't mean you should ignore what they are intended to teach.