线程终止时的 Java ExecutorService 回调

发布于 2024-11-05 00:00:07 字数 583 浏览 1 评论 0原文

我正在使用缓存线程池 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

谢谢,

施瑞亚斯

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清眉祭 2024-11-12 00:00:07

在您的 ThreadFactory 代码中,创建 Thread 实例,以便它将尝试执行 Runnable 的工作它是为然后finally 完成清理工作而创建的。像这样:

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文