Detect when the idle ThreadPoolExecutor thread is killed

advertisements

I am using ThreadPoolExecutor to manage the number of threads, I can catch the event of creating a new Thread for ThreadPool via ThreadFactory->newThread() But I do now know how to catch the event of killing Thread which stays idle for 2minutes as following configuration.

I hae searched a listener method but could not find.

public abstract class ThreadPoolEventProcessor<E>  implements ThreadFactory{

   private BlockingQueue<Runnable> taskQueue;
   private ThreadPoolExecutor executor;

   protected ThreadPoolEventProcessor(int coreThreadSize, int maxQueueSize) {
      taskQueue = new LinkedBlockingQueue<Runnable>(maxQueueSize);
      executor = new ThreadPoolExecutor(coreThreadSize, coreThreadSize * 5, 2L, TimeUnit.MINUTES, taskQueue,this);
      executor.prestartAllCoreThreads();
   }

  public Thread newThread(Runnable r) {
      return new Thread(r, getWorkerName());
    }


In ThreadPoolExecutor class there is a set of Workers, which are runnable classes ran by Threads in the pool.

When a worker is done workerDone call back executes. And there you see a tryTerminate method being called. That is the method deciding if to terminate thread or not. You should be able to debug at that point

   /**
 * Performs bookkeeping for an exiting worker thread.
 * @param w the worker
 */
void workerDone(Worker w) {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        completedTaskCount += w.completedTasks;
        workers.remove(w);
        if (--poolSize == 0)
            tryTerminate();
    } finally {
        mainLock.unlock();
    }
}


/* Termination support. */

/**
 * Transitions to TERMINATED state if either (SHUTDOWN and pool
 * and queue empty) or (STOP and pool empty), otherwise unless
 * stopped, ensuring that there is at least one live thread to
 * handle queued tasks.
 *
 * This method is called from the three places in which
 * termination can occur: in workerDone on exit of the last thread
 * after pool has been shut down, or directly within calls to
 * shutdown or shutdownNow, if there are no live threads.
 */
private void tryTerminate() {
    if (poolSize == 0) {
        int state = runState;
        if (state < STOP && !workQueue.isEmpty()) {
            state = RUNNING; // disable termination check below
            addThread(null);
        }
        if (state == STOP || state == SHUTDOWN) {
            runState = TERMINATED;
            termination.signalAll();
            terminated();
        }
    }
}