Home » Java programming language

Java Thread Class static boolean holdLock(Object o) method with Example

Java Thread Class static boolean holdLock(Object o) method: Here, we are going to learn about the static boolean holdLock(Object o) method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 21, 2019

Thread Class static boolean holdLock(Object o)

  • This method is available in package java.lang.Thread.holdLock(Object obj).
  • This method is used to lock the current thread on the specified object is given in the method.
  • This method is static so we can access this method with the class name too.
  • The return type of this method is boolean so it returns true or false if returns true indicating the current thread to be locked on the given object in the method else return false.
  • This method raises an exception if the object is null.

Syntax:

    static boolean holdLock(Object o){
    }

Parameter(s):

We pass only one object as a parameter in the method of the Thread i.e. Object obj so the obj on which to test the lock ownership.

Return value:

The return type of this method is Boolean, it returns true if the monitor lock of this thread on the given object in the method, else it returns false.

Java program to demonstrate example of holdLock() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/

import java.lang.Thread;

class HoldLock extends Thread {

    static Thread t1;

    // Override run() of Thread class
    public void run() {

        // We will display the name of Current Thread
        System.out.println("The name of the Current thread is: " + Thread.currentThread().getName());

        // This method returns true if the thread holds 
        // the lock on the specified object

        // Here we are not locking object t1 here in synchronized block  
        System.out.println("Is thread t1 holds lock here? " + Thread.holdsLock(t1));

        // Here we are locking object t1 in synchronized block  
        synchronized(t1) {
            System.out.println("Is thread t1 holds lock here? " + Thread.holdsLock(t1));
        }
    }

    public static void main(String[] args) {
        // Creating an object of HoldLock class
        HoldLock lock = new HoldLock();

        // Creating a thread object t1 
        t1 = new Thread(lock);

        // Calling start() method
        t1.start();
    }
}

Output

E:\Programs>javac HoldLock.java

E:\Programs>java HoldLock
The name of the Current thread is: Thread-1
Is thread t1 holds lock here ? false
Is thread t1 holds lock? true


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.