Java – intrinsic / monitor locking and inheritance
Background:
I'm reading Java concurrency in practice. Listing 2.7 contains the following code This example indicates that this code only works because the monitor lock is reentrant
I thought when you called super When dosomething(), it gets a lock on the base class object instead of the derived class object This means that this situation does not require re - entry Speaking of this, I also understand that both base class and derived class methods can change base class fields, so the locks they use must be universal (meaning I'm obviously wrong)
Question:
Does each object have an "internal" lock in the inheritance hierarchy, or only one "internal" lock associated with the most derived objects (or least derived objects) in the hierarchy?
public class Widget { public synchronized void doSomething() { ... } } public class LoggingWidget extends Widget { public synchronized void doSomething() { System.out.println(toString() + ": calling doSomething"); super.doSomething(); } }
Solution
Only one object – if you create a loggingwidget instance, you create only one object that contains all fields in the loggingwidget and all fields in the widget It is not like creating a loggingwidget instance, it refers to an instance of the widget
There is only one object, so there is only one lock, no matter where you synchronize