线程终止时的 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
谢谢,
施瑞亚斯
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的
ThreadFactory
代码中,创建Thread
实例,以便它将尝试
执行Runnable
的工作它是为然后finally
完成清理工作而创建的。像这样:In your
ThreadFactory
code, create the instance ofThread
such that it willtry
to do the work of theRunnable
it is created for and thenfinally
do your cleanup work. Like this: