简体   繁体   中英

Java ExecutorService callback on thread terminate

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM