14

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

Shreyas Shinde
  • 143
  • 1
  • 4
  • +1 for interesting question. I wonder if a finalizer would work? – Rom1 May 02 '11 at 21:43
  • @Rom1, someone had posted in answer suggesting implementing `finalize`. I think it is too bad they deleted it. What should be noted is that using `finalize` means incurring some performance hits in the GC and JVM. – Tim Bender May 02 '11 at 23:04
  • I tried to use the finalize approach but it didn't work. The method was not getting called. – Shreyas Shinde May 02 '11 at 23:14
  • @Tim, sure, the accepted answer looks a lot better than meddling with finalizers – Rom1 May 03 '11 at 07:13
  • It's more or less similar to : http://stackoverflow.com/questions/826212/java-executors-how-to-be-notified-without-blocking-when-a-task-completes/ – Ravindra babu Apr 06 '16 at 15:50

1 Answers1

14

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;
}
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • 1
    Another option is to use a fixed size thread pool and never clean up. Freed memory is never passed back to the OS, so you may be adding complexity without a benefit. – Peter Lawrey May 02 '11 at 22:15
  • 2
    but if the thing that needs to be cleaned up is a database connection, you can't just 'never clean up.' – stu Jan 07 '13 at 20:08