线程终止时的Java ExecutorService回调

我使用缓存线程池ExecutorService来运行一些异步后台任务。 我已经提供了我的ThreadFactory,它将线程分发给ExecutorService(只要它需要它们)。 我对缓存线程池的理解是,在线程空闲60秒后,它由ExecutorService终止。

当我的线程即将被终止时,我想执行一些状态清理。 实现这一目标的最佳方法是什么? ExecutorService不容易为线程的生命周期提供钩子。

我不想关闭我的ExecutorService – 对于在它们到来时运行任务很有用。

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 

谢谢,

Shreyas

在你的ThreadFactory代码中,创建Thread的实例,这样它将try完成它为其创建的Runnable的工作,然后finally完成清理工作。 喜欢这个:

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