Background:
I'm reading Java Concurrency in Practice, and Listing 2.7 has the following code. The example states that this code only functions because monitor locks are re-entrant.
I would have originally thought that when you called super.doSomething()
then it would have acquired a lock on the base class object and not the derived class object. That would mean this situation would not require re-entrancy. Having said this, I also understand that both base class and derived class methods can alter base class fields, so the lock they use must be common (meaning I was obviously mistaken).
Question:
Is there one "intrinsic" lock per object in an inheritance hierarchy, or one "intrinsic" lock associated with the most derived object (or least derived object) in the hierarchy only?
public class Widget {
public synchronized void doSomething() {
...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
I would have originally thought that when you called super.doSomething() then it would have acquired a lock on the base class object and not the derived class object.
There's only one object - if you create an instance of LoggingWidget
, there's only one object created, with all the fields from LoggingWidget
and also all the fields from Widget
. It's not like it creates an instance of LoggingWidget
that refers to an instance of Widget
.
There's only one object, and therefore only one lock, wherever you synchronize on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With