Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically determine which Java thread holds a lock

Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?

like image 201
Johan Lübcke Avatar asked Sep 08 '08 20:09

Johan Lübcke


People also ask

How do you check if a thread holds a lock in Java?

You can check the lock on the particular object by calling wait() or notify() method on that object. If the object does not hold the lock, then it will throw llegalMonitorStateException . 2- By calling holdsLock(Object o) method. This will return the boolean value.

Which method can be used to find that thread holds lock?

The java. lang. Thread. holdsLock() method returns true if and only if the current thread holds the monitor lock on the specified object.

Can Java notify specific threads?

You don't / can't notify a specific thread. You call notify() on a lock object. This wakes up one of the threads1 that is waiting on the lock.

How many threads can possess a lock at the same time?

For a thread to work on an object, it must have control over the lock associated with it, it must “hold” the lock. Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.


1 Answers

You can only tell whether the current thread holds a normal lock (Thread.holdsLock(Object)). You can't get a reference to the thread that has the lock without native code.

However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The ReentrantLock does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all.

There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.

like image 180
erickson Avatar answered Oct 09 '22 09:10

erickson