In this blog post we will talk and learn about one of very important multi Threading Java interview question and question is that Is it possible to check whether a thread holds a monitor lock on some given object?
We have method in class java.lang.Thread which provides the static method Thread.holdsLock(Object) that returns true if and only if the current thread holds the lock on the given object as argument to the method invocation.
Let’s try to understand using an Example..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.kkjavatutorials.client; public class MyTask { public synchronized void count(int number){ //Below statement will return true because count is a synchronized method within Class MyTask so without acquiring //object lock on current class object it is not possible to execute this method boolean holdsLock = Thread.holdsLock(this); System.out.println("Is Hold Lock inside count:"+holdsLock); for (int i = 1; i < number; i++) { System.out.print(i+" "); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kkjavatutorials.client; public class MyThread extends Thread { private MyTask myTask; public MyThread(MyTask myTask) { this.myTask = myTask; } @Override public void run() { System.out.println("Task Started..."); try { boolean holdsLock = Thread.holdsLock(myTask); System.out.println("Is Hold Lock inside run:"+holdsLock); Thread.sleep(1000); myTask.count(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(); System.out.println("Task Completed..."); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kkjavatutorials.client; public class ClientTest { public static void main(String[] args) { System.out.println("Main Start.."); MyTask myTask = new MyTask(); MyThread myThread = new MyThread(myTask); myThread.start(); System.out.println("Main End.."); } } |
Output
1 2 3 4 5 6 7 |
Main Start.. Main End.. Task Started... Is Hold Lock inside run:false Is Hold Lock inside count:true 1 2 3 4 5 6 7 8 9 Task Completed... |
That’s all about Is it possible to check whether a thread holds a monitor lock on some given object?
If you have any feedback or suggestion please feel free to drop in blow comment box.