如何在 JVM 控制台应用程序中处理 ^C?
当我的 JVM 运行(实际上是用 Scala 编写的,但我倾向于相信解决方案对于 Groovy、Clojure 或纯 Java 来说几乎是相同的)控制台程序被用户按 Ctrl< 终止时/kbd>+C (或者通过系统关闭顺序,我不知道程序是否有任何区别),如何确定应用程序修改的外部资源(数据库,文件、Web 服务抽象资源)是否处于可预测的、非逻辑损坏的状态?
When a JVM-ran (written in Scala actually, but I tend to believe that the solution is going to be pretty much the same for Groovy, Clojure or pure Java) console program of mine gets terminated by the user pressing Ctrl+C (or by the system shut-down sequence, I don't know if there is any difference for a program), how do I make sure the external resources the application modifies (databases, files, web service abstracted resources) are left in a predictable, non-logically-corrupt state?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试像其他人指出的那样实现关闭挂钩,但是:
我想,我相信您必须将事务上下文引入您的应用程序。对于数据库,这很简单,对于文件系统,您可以查看 Apache Commons Transaction
You can try to implement a shutdown hook as others pointed BUT:
I guess, you would have to introduce transactional context into your application I believe. For databases that's quite easy, for file system you can look into Apache Commons Transaction
看一下 Runtime.addShutdownHook。
您通常会这样使用它:
Take a look at Runtime.addShutdownHook.
You would typically use it as so:
您可以捕获此信号并关闭资源。大多数服务不需要正常关闭,但是您写入的文件通常需要关闭。
您可能只需要添加一个关闭挂钩即可。但我会根据你的情况对此进行测试。
You can trap this signal and close off resources. Most services do not need to be closed gracefully, however files you write to usually do.
It is possible just adding a shutdown hook is all you need. But I would test this for your situation.