Java ExecutorService callback on thread terminate

Shreyas Shinde picture Shreyas Shinde · May 2, 2011 · Viewed 9k times · Source

I am using cached thread pool ExecutorService to run some asynchronous background tasks. I've provided my ThreadFactory that hands out threads to the ExecutorService (whenever it needs them). My understanding of the cached thread pool is that after the thread is sitting idle for 60 seconds it is termniated by the ExecutorService.

I want to perform some state cleanup when my thread is about to be terminated. What is the best way to achieve this? The ExecutorService does not readily provide hooks into the thread's lifecycle.

I don't want to shutdown my ExecutorService - useful for running tasks as and when they come.

ExecutorService executor = Executors.newCachedThreadPool(new MyThreadFactory());

// Do some work
executor.submit(new MyCallable());

// Need a way for the ExecutorService to notify me when it is about to
// terminate my thread - need to perform some cleanup

Thanks,

Shreyas

Answer

Tim Bender picture Tim Bender · May 2, 2011

In your ThreadFactory code, create the instance of Thread such that it will try to do the work of the Runnable it is created for and then finally do your cleanup work. Like this:

public Thread newThread(final Runnable r) {
    Thread t = new Thread() {
        public void run() {
            try {
                r.run();
            } finally {
                //do cleanup code
            }
        }
    };
    return t;
}