Thread.holdsLock() is a true if the existing thread contains the monitor lock on a defined object. Otherwise, the function returns false.
static boolean holdsLock(Object obj)
obj: the objects for testing the lock possessionboolean_value: This method returns true if and only if the existing thread contains a monitor lock on the argument object. Otherwise, holdsLock() returns false.If the parameter obj is null, then the method generates NullPointerException.
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 packageimport java.lang.Thread;// Main classpublic class EdPresso implements Runnable {Thread thread; // our threadpublic EdPresso() {thread = new Thread(this);// it will help to call run() methodthread.start();}public void run() {/* it will return true if current threadcontains 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();}}
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.