Will the following code execute successfully?

Navjot Singh :

In Brian Goetz's Java Concurrency in Practice, there is following example which explains the reentrancy of the locks in Java as:

public class Widget {
  public synchronized void doSomething() {
    ...
  }
}

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

It says that because of the reentrancy of locks in Java, the above code will not lead to a deadlock, since the locks are attained on per-thread basis rather than per-invocation basis.

However, if we twist the example a bit like:

public class XYZ {
  public synchronized void someFunction() {
    ...
  }
}

public class SomeClass {
  private XYZ xyz;
  ...
  public synchronized void functionCalled() {
    ...
    xyz.someFunction();
  }
}

We call the functionCalled() of SomeClass and the lock is obtained on the object of SomeClass. Now, will the someFunction() get called or in other terms will the thread enter the someFunction() of xyz class. Will the synchronized function of XYZ class ask for lock on the object of XYZ class? I am a bit confused. Please clarify.

markspace :

Yes, the code above will ask for a lock on both SomeClass and the xyz object. This causes no problems however.

The xyz object is private, so there is no possibility that any thread will first lock xyz before invoking functionCalled(), thus there is no possibility of dead lock since the two locks here are always called in the order SomeClass -> xyz.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=103564&siteId=1