Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock Acquisition Order

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();
    }
}
like image 293
Lydon Ch Avatar asked Jan 23 '26 04:01

Lydon Ch


1 Answers

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.

like image 94
cletus Avatar answered Jan 25 '26 17:01

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!