Is there a way to get a list of waiting threads/number of waiting threads on an object?
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.
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.
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.
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.
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());
}
}
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