Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java list of waiting threads

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

like image 803
Rnet Avatar asked Oct 28 '11 12:10

Rnet


People also ask

What is wait () and notify () in multithreading?

Differences between wait() and notify()When wait() is called on a thread holding the monitor lock, it surrenders the monitor lock and enters the waiting state. When the notify() is called on a thread holding the monitor lock, it symbolizes that the thread is soon going to surrender the lock. 2.

What is wait () Java?

Simply put, wait() is an instance method that's used for thread synchronization. It can be called on any object, as it's defined right on java. lang. Object, but it can only be called from a synchronized block. It releases the lock on the object so that another thread can jump in and acquire a lock.

What are waiting threads?

A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object. wait() on an object is waiting for another thread to call Object. notify() or Object.


2 Answers

If you are using the synchronized keyword - no. But if you are using the java.util.concurrent locks, you can.

ReentrantLock has a protected method getWaitingThreads(). If you extend it, you can make it public.

Update: You are using .wait() and .notify(), so you can manually fill and empty a List<Thread> - before wach .wait() call list.add(Thread.currentThread(), and remove it before each notify. It's not perfect, but actually you shouldn't need such a list.

like image 156
Bozho Avatar answered Sep 29 '22 06:09

Bozho


You can use the JMX classes to inspect the threads:

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

Each blocked thread has a non null LockInfo associated that will let you identify on what object it's 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());
    }
}
like image 38
Emmanuel Bourg Avatar answered Sep 29 '22 06:09

Emmanuel Bourg