Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intrinsic/Monitor Locks and Inheritance

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();
    }
}
like image 333
John Humphreys Avatar asked Feb 13 '23 06:02

John Humphreys


1 Answers

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.

like image 129
Jon Skeet Avatar answered Feb 15 '23 10:02

Jon Skeet