Share on Google+Share on Google+

Java Thread HoldsLock

Advertisement
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

Advertisements

Advertisement

Posted on: October 23, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.