With the following code, if a thread calls LoggingWidget.doSomething(), what is the order of lock acquisition that the thread has to go through? (i.e. does it get the Lock on LoggingWidget first, and then gets the lock on Widget ? )
public class Widget {
public synchronized void doSomething() {
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
The lock in this case is on this so there is only one lock, that being the instance. If there are more than one instance, each has an entirely separate lock regardless of whether it is a Widget or a LoggingWidget.
Let me put it another way. Your code is semantically equivalent to:
public class Widget {
public void doSomething() {
synchronized (this) {
// do stuff
}
}
}
public class LoggingWidget extends Widget {
public void doSomething() {
synchronized (this) {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
}
Only one of these methods is called so there's only one lock.
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