List of Java Pending Threads

Is there a way to get a list of pending threads / number of pending threads on an object?

+6
source share
3 answers

If you use the synchronized - no. But if you use java.util.concurrent locks, you can.

ReentrantLock has a protected getWaitingThreads() method. If you expand it, you can make it publicly available.

Update. You use .wait() and .notify() so you can manually populate and empty the List<Thread> - before calling .wait() list.add(Thread.currentThread() and delete it before each notification. This is not ideal, but you don’t really need such a list.

+10
source

You can use JMX classes to check threads:

 ThreadInfo[] infos = ManagementFactory.getThreadMXBean().dumpAllThreads(true, true); 

Each blocked thread has an associated non-zero LockInfo , which will allow you to determine on which object it is waiting:

 for (ThreadInfo info : infos) { LockInfo lockInfo = info.getLockInfo(); if (lockInfo != null && lockInfo.getClassName().equals(lock.getClass().getName()) && lockInfo.getIdentityHashCode() == System.identityHashCode(lock)) { System.out.println("Thread waiting on " + lock + " : " + info.getThreadName()); } } 
+8
source

If you are on JDk 1.6, then ManagementFactory.getThreadMXBean() is the best way to find out about all threads waiting on an object. For JDK up to 1.6, you can use a group of threads to find out all the threads, and then check the stack stack to find out about the object. on which they are waiting.

+2
source

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


All Articles