确定ExecutorService的关闭时间
我有一个 ExecutorService 来处理一些任务。客户端线程可以调用ExecutorService
上的shutdown()
。我想在 ExecutorService 完全关闭后运行一些清理代码。是否有一种机制可以在 ExecutorService 完成关闭后运行回调方法。
注意:
- 我无法调用
shutdownNow()
- 清理代码必须在
shutdown()
完成后运行。 ExecutorService
是一个newCachedThreadPoolExecutor()
;
I have an ExecutorService
that processes some tasks. The client threads can call shutdown()
on the ExecutorService
. I want to run some cleanup code after the ExecutorService
has completely shutdown. Is there a mechanism to run a callback method after the ExecutorService
has completed its shutdown.
NOTE:
- I cannot call
shutdownNow()
- The clean-up code must run after the
shutdown()
is completed. - The
ExecutorService
is anewCachedThreadPoolExecutor()
;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
启动另一个线程/executor-managed-runnable来检查
ExecutorService.awaitTermination(...)
在循环中的 try-catch 语句中直到返回true
,然后运行关闭处理代码。该循环是必要的,因为该方法在中断时可能会过早返回。像这样的东西:
Start another thread/executor-managed-runnable that checks
ExecutorService.awaitTermination(...)
in a try-catch statement in a loop until it returnstrue
, then run your shutdown handling code. The loop is necessary because the method might return prematurely when interrupted.Something like this:
我会扩展并覆盖:
类似的东西
I would extends and override:
Something like that
好吧,如果您调用 executorService.invokeAll(myListOfCallableTasks) 和 executorService.shutDown() 调用的线程将阻塞,直到所有任务完成:
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)
Well, if you call executorService.invokeAll(myListOfCallableTasks) and them executorService.shutDown() the thread calling that will block until all the tasks are finished:
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)