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 objectBelow 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);