问题描述
我正在编写一个理论上可以在不同环境中使用的Java客户端:Java main(),servlet容器或依赖注入。
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.
这种方法的问题是客户端的用户不知道内部线程池的实现将会看到他的或者她的应用程序在关机时挂起。我的用户需要知道向库发送shutdown()消息。
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.
我想知道是否可以采取任何其他替代方法,一方面允许我为我的连接启动一个线程池;并且,另一方面,捕获一些事件,可能是一个JVM事件,表明JVM正在关闭,这将允许我调用我的shutdown()实现。
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.
推荐答案
虽然你可以像之前的建议一样添加钩子,但你仍然可能遇到的问题是线程池仍然有活动线程。
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.
我相信如果你将你的个别线程标记为守护进程(通过Thread.setDaemon方法),那么如果只剩下守护进程线程,JVM将无法保持活动状态。
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.
来自JavaDoc:
使用此方法,如果您的主非守护程序线程被终止,JVM将不会因为其他线程而挂起线程运行,这会触发你的关闭挂钩,而不必显式地向各个线程发送终止指令。
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.
这篇关于如何实现在执行结束时自动关闭的线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!