Search code examples
javamultithreadinglockingwait

Ways to acquire the intrinsic lock for the thread calling the wait method


Logically, it is understood that a thread calling the wait method should have already acquired the intrinsic lock of the object that wait is being called on.

It is stated in the oracle tutorial here, that "invoking wait inside a synchronized method of the object is a simple way to acquire the intrinsic lock", which implies that there may be at least another way to acquire the lock.

My question is, in order to invoke wait, is there other ways to acquire the intrinsic lock other than invoking wait inside the synchronized method? ... and what are they?


Solution

  • A few (closely-related) others that spring to mind:

    • In a synchronized block:

      synchronized (this) {
        wait();
      }
      
    • In a non-synchronized method, called from inside a sychronized method:

      synchronized void a() {
        b();
      }
      
      void b() {
        wait();
      }
      
    • In a non-synchronized method, called from inside a sychronized block:

      synchronized (this) {
        b();
      }
      
      void b() {
        wait();
      }