线程终止时的Java ExecutorService回调 [英] Java ExecutorService callback on thread terminate

查看:164
本文介绍了线程终止时的Java ExecutorService回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我希望在我的线程即将被终止时执行一些状态清理。实现这一目标的最佳方法是什么? 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.

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

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

谢谢,

Shreyas

推荐答案

ThreadFactory 代码中,创建 Thread 的实例,以便它将尝试来完成 Runnable 的工作,然后再创建 做你的清理工作。像这样:

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

这篇关于线程终止时的Java ExecutorService回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆