How to find which thread currently owns a lock in java

I have a synchronous method in a singleton class that is called by many threads at the same time. Is there any java API to check which thread currently holds the lock?

+4
source share
4 answers

Perhaps you can print Thread.currentThread() in a synchronized method.

+2
source

The exact answer asked by erickson [ here ]

Question: Programmatically determine which Java thread holds a lock?


Answer:

You can only find out, the thread has a normal lock (Thread.holdsLock (object)). You cannot get a link to a thread that has a lock without inline code.

However, if you are doing something complicated with threading, you might want to check out java.util.concurrent packages. ReentrantLock allows you to get its owner (but its protected method, so you have to distribute this). Depending on your application, it is entirely possible that using concurrency packages, you will be sure that you do not need a lock owner in the end.

There are no software methods for finding lock owners, such as the JVM signaling the release of a dump stream in stderr, which are useful for determining the cause of deadlocks.

By the way, please take a look at the following link. It provides all the information about flow related aspects:

+3
source

jvm ThreadMXBean gives you access to all kinds of thread related information, including those threads that are blocked.

+2
source

If you are just studying software debugging to find out which thread is blocking and which one is blocked, I would suggest just getting a stream dump in real time. I would not use this logic as part of the normal program flow.

http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/

0
source

Source: https://habr.com/ru/post/1340946/


All Articles