Extended classes synchronized methods locking
concurrency, java, multithreading
Solution
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).
Problem
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()`?