Search code examples
javaconcurrencylockingreentrancy

Reentrant locking


A bit of help please, consider the bit of code below.

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 read that when doSomething() in LoggingWidget is called, the JVM will try to acquire a lock on LoggingWidget first and then on Widget.

I am curious to know the reason. Is it because the JVM knows that doSomething() has a call to super.doSomething() or because calling a subclass method will always acquire a lock on the superclass as well.

Cheers


Solution

  • You are mistaken - the locks are obtained at the instance level. There is only one lock in your example because there is only one instance created when you say:

    Widget w = new LoggingWidget
    

    You can view locks (also known as monitors, mutexes or semaphores) as being individually "attached" to every object instance in the JVM.

    If you had another synchronized method on the LoggingWidget subclass, you would see this to be true. It would not be possible to call this (new) method and the doSomething method at the same time [with different threads on same object].

    This also holds true for another synchronized method on the superclass (i.e. it is not affected in any way by methods being overridden).