What is the Thread holdsLock() function in Java?
Thread.holdsLock() is a 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 returnstrueif and only if the existing thread contains a monitor lock on the argument object. Otherwise,holdsLock()returnsfalse.
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 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();}}
Explanation
-
The function will return
trueif there is a monitor lock on thethisthread. -
When a thread encounters a
synchronizedblock, 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 therun()function.run()contains the implementation of thethisthread.