Is there a way to get a list of waiting threads/number of waiting threads on an 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 are on JDk 1.6 then ManagementFactory.getThreadMXBean() is the best way to find out about all the threads waiting on object
For JDK before 1.6 you can use thread group to find out all the threads and then inspect thread stack to find out about object on which they are waiting.