Thread holdslock() method in java

Let’s learn thread holdslock(object obj) method in java.

Thread holdslock(object obj) method in java

holdslock(object obj) method returns true if and only if the current thread holds the monitor lock on the specified object.

Thread.holdsLock() method is designed to allow a program to assert that the current thread already holds a specified lock:

assert Thread.holdsLock(obj);

Syntax

public static boolean holdsLock(Object obj)

Parameters

obj the object on which to test lock ownership

Returns

true if the current thread holds the monitor lock on the specified object.

Example

class HoldsLockMethodDemo implements Runnable
{
   Thread t;
   public HoldsLockMethodDemo() 
   {
      t = new Thread(this);
      t.start();
   }
   public void run() 
   {
      System.out.println("Does thread Holds Lock = " + Thread.holdsLock(this));
      synchronized (this) 
      {
         System.out.println("Does thread Holds Lock = " + Thread.holdsLock(this));
      }
   }
   public static void main(String[] args) 
   {
      new HoldsLockMethodDemo();
   }
}

Output:

Does thread Holds Lock = false
Does thread Holds Lock = true


Also read – interface in java