Java list of waiting threads

前端 未结 3 1099
忘掉有多难
忘掉有多难 2021-02-15 12:43

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

相关标签:
3条回答
  • 2021-02-15 12:57

    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.

    0 讨论(0)
  • 2021-02-15 13:02

    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());
        }
    }
    
    0 讨论(0)
  • 2021-02-15 13:12

    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.

    0 讨论(0)
提交回复
热议问题