About NewTechnoBuzz
Contact Us

Friday, July 18, 2014

How to check if a thread holds lock on a particular object in Java

A lock is a thread synchronization mechanism like synchronized blocks except locks can be more sophisticated than Java's synchronized blocks. Locks are created using synchronized blocks, so it is not like we can get totally rid of the synchronized keyword.

Sometimes, we need to find at run time that whether a java thread has lock on a particular object.
E.g. Suppose, we have a thread empThread and an object ("employee") of Employee class. At runtime, I want to find out whether thread empThread has lock on employee object or not?
In Java 5, java.util.concurrent.locks package contains several lock implementations, so you may not have to implement your own locks. But, you will still need to know how to use them, and it can still be useful to know the theory behind their implementation.

Ways to find if thread holds lock on object

Below are the ways to find out if thread holds lock on object:
  • Thread class has a static method called holdsLock(Object obj) which returns true or false based on whether threads holds lock on object passed. But, using this method, you can only tell whether the current thread holds a normal lock on the object. You can't get a reference to the thread that has the lock without native code.
  • Java 6 provides a way to get locks held by threads using reflection.
ThreadMXBean thread = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfo = thread.getThreadInfo(thread.getAllThreadIds(), true, true);

I did my best to explain how to check if a thread holds lock on a particular object in Java. But, comments, suggestions and feedback are welcome to make this article more valuable.