user2653926
user2653926

Reputation: 604

Extended classes synchronized methods locking

Suppose this code

class A
{
    public synchronized void methodA()
    {
        // ...
    }
}

class B extends A
{
    @Override
    public synchronized void methodA()
    {
        // ...
        super.methodA();
    }
}

What lock should be acquired by any thread if it wants to access methodA function of class B and methodA of super class A by super.methodA()?

Upvotes: 5

Views: 1321

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136162

When you call B b = new B(); b.methodA(); current thread will aquire lock on b , enter B.methodA and call A.methodA. Both methods share the same object and when entering A.methodA the thread will just re-enter the same lock which it already owns.

Upvotes: 3

Mattias Buelens
Mattias Buelens

Reputation: 20179

A synchronized method is equivalent to a method with its body wrapped in a synchronized(this) block. Thus, this:

public synchronized void methodA()
{
    // ...
}

is the same as:

public void methodA()
{
    synchronized(this) {
        // ...
    }
}

Now, you can easily see that both methodA implementations lock on the same object, namely the this object. That is, if a thread is in a synchronized method of the superclass, it also prevents other threads from entering any synchronized method of the subclass (and vice versa).

Since synchronized locks are re-entrant, successfully entering B.methodA means that you can also immediately enter super.methodA (as you already have the lock).

Upvotes: 2

Related Questions