holdsLock(object) method in java to find whether current thread holds the lock on monitor of specified object.


Contents of page :

  • holdsLock(object) method >
  • Program to find whether thread hold lock on monitor of specified object or not >
  • Output analyzation >


holdsLock(object) method >
holdsLock(object) method can be used to find out whether current thread holds the lock on monitor of specified object.

holdsLock(object) method returns true if the current thread holds the lock on monitor of specified object.

Program to find whether thread hold lock on monitor of specified object or not >
class MyRunnable implements Runnable{
   public void run(){
          synchronized (this) {
                 System.out.println("inside sync block, thread hold lock "
                              + "on object monitor - "+Thread.holdsLock(this));
          }
          System.out.println("outside sync block, thread hold lock "
                       + "on object monitor - "+Thread.holdsLock(this));
   }
  
}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class HoldLockMethodTest {
   public static void main(String...args){
          MyRunnable runnable=new MyRunnable();
          Thread thread1=new Thread(runnable,"Thread-1");
          thread1.start();
  
   }
}
/*OUTPUT
inside sync block, thread hold lock on object monitor - true
outside sync block, thread hold lock on object monitor - false
*/


Output analyzation >
When we were inside sync block, thread hold lock on object monitor = true.
But when we were outside sync block, thread hold lock on object monitor = false

RELATED LINKS>



Important Thread methods (salient features, usage with programs)>

Sleep() method in threads - 10 key features with programs

Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.

Daemon threads - 12 salient features of Daemon Thread

2 alternate ways to stop thread, as stop() method is deprecated

Join() method - 10 salient features of join

Thread isAlive() method

interrupt() method of thread in java

holdsLock(object) method to find whether current thread holds the lock on monitor of specified object.

Thread priorities - setPriority() and getPriority() methods

Using Suspend and resume method in threads



Methods for Adding ShutdownHook and handling uncaught runtime exception >

Threads addShutdownHook method in java

Handling uncaught runtime exception generated in run method using - setDefaultUncaughtExceptionHandler method




No comments:

Post a Comment