I have a synchronized method in a singleton class which is called by many threads simultaneously. Is there any java API available to check which thread is currently owning the lock ?
Precise answer given by erickson
[here]
Question: Programmatically determine which Java thread holds a lock ?
Answer :
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.
By the way,please have a look at the following link. It provides all information about thread related aspects :
You could perhaps print out Thread.currentThread()
in your synchronized method.
The jvm ThreadMXBean gives you access to all kinds of thread related info, including which threads own which locks.
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