问题
Per the ThreadPoolExecutor doc (Java ThreadPoolExecutor), if I create an executor service like so:
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
and when #threads > corePoolSize, idle threads will be killed. I wanted to call some application specific cleanup code when the ThreadPoolExecutor kills any thread. I wasn't able to get a clear way to do so. Appreciate any help. Thanks in advance.
回答1:
the correct way to do this is by extending Thread and running your cleanup code after the run() method returns, like so:
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r) {
@Override
public void run() {
super.run();
//DO YOUR CLEANUP HERE
}
};
}
};
new ThreadPoolExecutor(1, 10, 10, TimeUnit.SECONDS, workQueue, threadFactory);
interrupt will almost definitely not get called in your scenario, since it will only be called when shutting down an active executor (and even then, not always).
by calling cleanup directly after run your cleanup code gets called right before the thread dies (a thread dies after the runnable's run() method returns).
来源:https://stackoverflow.com/questions/25104668/java-threadpoolexecutors-idle-thread-shutdown-calling-custom-cleanup-code