如何实现执行结束自动关闭的线程池?
我正在编写一个 Java 客户端,理论上它可以在不同的环境中使用:Java main()、servlet 容器中或通过依赖项注入。
客户端实现内部连接线程池。
这种方法的问题在于,不知道内部线程池已实现这一事实的客户端用户将看到他或她的应用程序在关闭时“挂起”。我的用户需要知道向图书馆发送 shutdown() 消息。
我想知道是否可以采取任何其他替代方法,一方面,允许我为我的连接启动线程池;另一方面,捕获一些事件,可能是 JVM 事件,表明 JVM 正在关闭,这将允许我调用 shutdown() 实现。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管您可以按照之前的建议添加挂钩,但您仍然可能遇到的问题是线程池仍然具有活动线程。
我相信,如果您将各个线程标记为“守护进程”(通过 Thread.setDaemon 方法),那么如果仅留下守护线程,JVM 将不会保持活动状态。
来自 JavaDoc:
使用此功能,如果您的主非守护线程被终止,JVM 不会因为其他线程正在运行而“挂起”,并且这会触发您的关闭挂钩,而无需向各个线程显式发送终止指令。
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:
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()
。 http://blog.yohanliyanage.com/2010/ 10/know-the-jvm-2-shutdown-hooks/ 有不错的解释。这有帮助吗?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?如果问题是代码的用户不知道有一个线程池需要关闭,也许解决方案是让他们知道这一点?在相关类的工厂方法或构造函数中,将 ExecutorService 用作参数,因此调用者对其生命周期负责。即使用依赖注入来推动策略向上。
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.