Friday, 1 August 2014

Check whether thread holds lock on object ?

Thread class provides a 'holdsLock' method which returns true if the current thread holds the monitor lock on the specified object, else false.

public static boolean holdsLock(Object obj)

Returns true if the current thread holds the monitor lock on the specified object else false.

public class Employee{

}

public class HoldLockEx implements Runnable{
    Employee emp;
    
    HoldLockEx(Employee emp){
        this.emp = emp;
    }
    
    public void unHoldLock(){
        System.out.println("Is thread holds the lock " + Thread.holdsLock(emp));
    }
    
    public void holdLock(){
        synchronized(emp){
            System.out.println("Is thread holds the lock " + Thread.holdsLock(emp));
        }
    }
    
    @Override
    public void run(){
        unHoldLock();
        holdLock();
    }
    
    public static void main(String args[]){
        HoldLockEx task = new HoldLockEx(new Employee());
        Thread t1 = new Thread(task);
        t1.start();
    }
}

Output
Is thread holds the lock false
Is thread holds the lock true





                                                             Home

No comments:

Post a Comment