线程终止时的Java ExecutorService回调

Shr*_*nde 13 java multithreading executorservice threadpool

我使用缓存线程池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
Run Code Online (Sandbox Code Playgroud)

谢谢,

Shreyas

Tim*_*der 14

在您的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;
}
Run Code Online (Sandbox Code Playgroud)

  • 但如果需要清理的东西是数据库连接,那么你就不能"永远不要清理". (2认同)