Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which thread currently owns the lock in java

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 ?

like image 937
ihavprobs Avatar asked Feb 23 '11 11:02

ihavprobs


3 Answers

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 :

  • JVM's ThreadMXBean
like image 159
Saurabh Gokhale Avatar answered Nov 10 '22 15:11

Saurabh Gokhale


You could perhaps print out Thread.currentThread() in your synchronized method.

like image 2
adarshr Avatar answered Nov 10 '22 16:11

adarshr


The jvm ThreadMXBean gives you access to all kinds of thread related info, including which threads own which locks.

like image 2
jtahlborn Avatar answered Nov 10 '22 15:11

jtahlborn