How to report thread pool is empty in Java

I have a thread pool created using

java.util.concurrent.ThreadPoolExecutor 

Anyway, can I wait until the pool is idle? By this, I mean that all threads are down and waiting in the queue for nothing.

I searched on the internet and all solutions do not work for me. For example, I do not want to disable the pool, so waitTermination () will not work. I also know how to getTaskCount (), but I do not want to continue polling the pool that the processor drops.

This is a big project, and I don’t want to change all the tasks running in the pool, so I'm looking for some solution that does not depend on the collaboration of the task. So latches or barriers don't work for me.

+4
source share
2 answers

You can subclass ThreadPoolExecutor and add hooks with beforeExecute and afterExecute to track the progress of the task as you like, including basic math, to count the current tasks being performed. There is also direct access to the queue using getQueue ().

Between them, you can easily implement the tracking you are asking for. I'm curious what your use case is ... what will you do with the pool when it is empty?

+4
source

I am wondering if this will work in a real environment. It involves subclassing ThreadPoolExecutor and passing it to IdleListener :

  @Override protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); listener.working(); } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); long activeCount = getTaskCount() - getCompletedTaskCount(); if (activeCount == 1) // yes, one { listener.idle(); } } 

Interface:

  interface IdleListener { void working(); void idle(); } 
+3
source

All Articles