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

*爱你&永不变心* 提交于 2019-12-22 13:01:02

问题


I'm writing a Java client which could theoretically be used in a different environment: Java main(), in a servlet container, or via dependency injection.

The client implements internal connection thread pooling.

The problem with this approach is that users of the client that are unaware of the fact that an internal thread pool is implemented will see his or her application "hang" on shutdown. My users need to know to send a shutdown() message to the library.

I'm wondering if any other alternative approach could be taken that would, on one hand, allow me to start a thread pool for my connections; and, on the other hand, catch some event, perhaps a JVM event, that indicates the JVM is going down, which will allow me to call my shutdown() implementation.


回答1:


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.




回答2:


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?




回答3:


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.



来源:https://stackoverflow.com/questions/4769429/how-to-implement-thread-pool-that-will-automatically-shutdown-at-end-of-executio

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