如何确保在退出Java应用程序之前运行一段代码 [英] How to ensure a piece of code is run before exiting a java application

查看:896
本文介绍了如何确保在退出Java应用程序之前运行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个许可的API,该API具有从具有有限数量的许可的许可服务器中获取/释放许可对象的方法.在我的应用程序开始时,我调用了获取许可证的方法,但是我想确保即使我的程序突然终止/崩溃(异常,SIGTERM等),也可以释放该许可证.关闭挂钩是解决此问题的最佳方法吗?

I'm using a licensed API which has a method to acquire/release a license object from a license server that has a finite number of licenses. At the beginning of my application, I call the method to acquire the license, but I want to make sure that this gets released even if my program terminates/crashes abruptly (exceptions, SIGTERM, etc). Is the shutdown hook the best way to approach this issue?

推荐答案

@thedan关于JVM硬崩溃是正确的.如果JVM崩溃严重或获得SIGKILL,则在退出前将没有机会运行任何东西.在那种情况下,您无法采取任何补救措施来解决此问题. (但是其他语言的情况也一样……)

@thedan is correct about hard JVM crashes. If a JVM crashes hard or it gets a SIGKILL, it won't get a chance to run anything before exiting. There is nothing you can do to remedy this in Java in that scenario. (But the situation is the same in other languages too ...)

但是,如果JVM为响应所有非dameon线程的结束而进行有序关闭,则调用System.exit()并获取SIGINT等,则JVM将尝试运行关闭钩子. 问题与解答页面和 javadocs .

However if the JVM does an orderly shutdown in response to all non-dameon threads ending, calling System.exit(), getting a SIGINT and so on, then the JVM will attempt to run the shutdown hooks. There is more information on Java's shutdown hook mechanisms in the Q&A page and the javadocs.

finally方法也是一种选择,但是仅当所讨论的线程在JVM退出之前终止时才有效.如果调用System.exit()或JVM被信号终止,则不会发生这种情况.关机挂钩可在更多情况下工作.

The finally approach is also an option, but is only works if the thread in question is terminated before the JVM exits. This won't happen if System.exit() is called or the JVM is terminated by a signal. Shutdown hooks work in more situations.

(在我看来,finally实际上是在单个线程上而不是整个应用程序上执行清理操作.但是,如果您的应用程序仅包含一个线程...或者它具有负责执行该操作的主线程有序关闭...然后finally可以用于应用程序清理.)

(To my mind, finally is really for performing clean on a single thread rather than for the entire application. However if your application consists of just one thread ... or if it has a master thread that is responsible for orderly shutdown ...then finally can serve the purpose of application cleanup.)

真正的解决方案是配置许可的API,以便许可管理器可以检测使用许可的应用程序实例何时消失而不释放它.是否可行取决于许可证管理器.

The real solution is to configure the licensed API so that the license manager can detect when the application instance using a license goes away without releasing it. Whether this is possible depends on the license manager.

这篇关于如何确保在退出Java应用程序之前运行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆