How to implement thread pool that will automatically shutdown at end of execution?

安稳与你 提交于 2019-12-06 07:55:25

Although you can add hooks, as was previous suggested, the problem you're still likely to have is the thread-pool still having active threads.

I believe that if you mark your individual threads as "daemons" (via Thread.setDaemon method) then the JVM will not keep alive if only daemon threads are left.

From the JavaDoc:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

Using this, if your primary non-daemon thread is terminated, the JVM won't "hang-up" because of the other thread running, and this trigger your shutdown hooks without having to explicitly send terminate instructions to the various threads.

Runtime.getRuntime().addShutdownHook() would be the thing I would think of. http://blog.yohanliyanage.com/2010/10/know-the-jvm-2-shutdown-hooks/ has decent explanation. Does that help?

If the problem is that users of your code are not aware there is a thread pool to be shutdown, perhaps the solution is to make them aware of it? In the factory method or constructor for the relevant class, have the ExecutorService to use as an argument, so the caller is responsible for its lifecycle. That is, use depency injection to push policy upwards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!