views:

283

answers:

2

I have a thread pool created using

   java.util.concurrent.ThreadPoolExecutor

Is there anyway I can wait till the pool is idle? By which I mean all the threads are not running and nothing is waiting in the queue.

I searched the web and all the solutions don't work for me. For example, I don't want shutdown the pool so awaitTermination() wouldn't work. I also know how to getTaskCount() but I don't want keep polling the pool, which wastes CPU.

This is a large project and I don't want change all the tasks running in the pool so I am looking for some solution that don't rely on task cooperation. So latches or barriers don't work for me.

+2  A: 

You could subclass ThreadPoolExecutor and add hooks with beforeExecute and afterExecute to track task execution however you like, including basic math to count the currently executing tasks. There is also direct access to the Queue with getQueue().

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

TREE
Thanks. I was hoping there is a way with existing pool implementations. I have a maintenance thread which slows system down so it only does work when thread pool is idle.
ZZ Coder
+1  A: 

I am wondering if this would work in a real world environment. It involves subclassing ThreadPoolExecutor and passing it an 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();
    }
  }

The interface:

  interface IdleListener
  {
    void working();
    void idle();
  }
eljenso