Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?
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.
The java. lang. Thread. holdsLock() method returns true if and only if the current thread holds the monitor lock on the specified object.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With