What is the Thread holdsLock() function in Java?

Thread.holdsLock() is a staticstatic indicates that the particular member belongs to a type itself, rather than to an instance of that type. function that returns true if the existing thread contains the monitor lock on a defined object. Otherwise, the function returns false.

Syntax


static boolean holdsLock(Object obj)

Parameters

  • obj: the objects for testing the lock possession

Return value

  • boolean_value: This method returns true if and only if the existing thread contains a monitor lock on the argument object. Otherwise, holdsLock() returns false.

Exception

If the parameter obj is null, then the method generates NullPointerException.

Code

In the code snippet below, we have a main class named class EdPresso. Our goal is to understand the Thread.holdsLock() method, which returns true or false.

// import Thread class from package
import java.lang.Thread;
// Main class
public class EdPresso implements Runnable {
Thread thread; // our thread
public EdPresso() {
thread = new Thread(this);
// it will help to call run() method
thread.start();
}
public void run() {
/* it will return true if current thread
contains any monitor lock on defined object */
System.out.println("Before Locking:");
System.out.println("Holds Lock = " + Thread.holdsLock(this));
synchronized(this) {
System.out.println("After Locking:");
System.out.println("Holds Lock = " + Thread.holdsLock(this));
}
System.out.println("After Unlocking:");
System.out.println("Holds Lock = " + Thread.holdsLock(this));
}
public static void main(String[] args) {
new EdPresso();
}
}

Explanation

  • The function will return true if there is a monitor lock on the this thread.

  • When a thread encounters a synchronized block, it will own a monitor at such an instance. Therefore, it cannot be changed by another thread/program in line 23.

  • The start() function is used to create a new thread that will explicitly call the run() function. run() contains the implementation of the this thread.