Home Tutorial Java Core Java Thread HoldsLock

 
 

Share on Google+Share on Google+
Java Thread HoldsLock
Posted on: October 23, 2012 at 12:00 AM
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
Advertisement

Related Tags for Java Thread HoldsLock :


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.

Posted on: October 23, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com