Java Thread HoldsLock


 

Java Thread HoldsLock

In this tutorial, you will learn how to lock a thread with example in Java.

In this tutorial, you will learn how to lock a thread with example in Java.

Java Thread HoldsLock

In this tutorial, you will learn how to lock a thread with example in Java.

Thread HoldsLock  :

It is easy to use synchronized code for locking but there is some limitation too. java.util.concurrent.locks package provides locking way.
Synchronized method provides implicit locks for locking your current object.

public static boolean holdsLock(Object obj): This method returns true if the current thread holds the monitor lock on the given object. It throws NullPointerException if argument obj is null.

Example :  In this example we are using Thread.holdsLock to lock the object.

public class ThreadHoldsLock implements Runnable {

	static Thread thread;

	public ThreadHoldsLock() {
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		System.out.println(this.getClass() + ", Hold Lock "
				+ Thread.holdsLock(this));
		synchronized (this) {
			System.out.println(this.getClass() + ", Hold Lock "
					+ Thread.holdsLock(this));
		}
		try {
			thread.wait();
		} catch (Exception e) {
			e.getMessage();
		}
	}

	public static void main(String[] args) {
		new ThreadHoldsLock();
	}
}

Output :

class ThreadHoldsLock, Hold Lock false
class ThreadHoldsLock, Hold Lock true

Ads