如何在 JVM 控制台应用程序中处理 ^C?

发布于 2025-01-02 12:35:56 字数 214 浏览 2 评论 0原文

当我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白云悠悠 2025-01-09 12:35:56

您可以尝试像其他人指出的那样实现关闭挂钩,但是:

在极少数情况下,虚拟机可能会中止,即停止
运行而不完全关闭。当虚拟
机器从外部终止,例如使用 SIGKILL 信号
在 Unix 上或在 Microsoft Windows 上调用 TerminateProcess。虚拟的
如果本机方法出错,机器也可能中止,例如,
损坏内部数据结构或尝试访问
不存在的记忆。如果虚拟机中止则无法保证
可以决定是否运行任何关闭挂钩。

我想,我相信您必须将事务上下文引入您的应用程序。对于数据库,这很简单,对于文件系统,您可以查看 Apache Commons Transaction

You can try to implement a shutdown hook as others pointed BUT:

In rare circumstances the virtual machine may abort, that is, stop
running without shutting down cleanly. This occurs when the virtual
machine is terminated externally, for example with the SIGKILL signal
on Unix or the TerminateProcess call on Microsoft Windows. The virtual
machine may also abort if a native method goes awry by, for example,
corrupting internal data structures or attempting to access
nonexistent memory. If the virtual machine aborts then no guarantee
can be made about whether or not any shutdown hooks will be run.

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

时常饿 2025-01-09 12:35:56

看一下 Runtime.addShutdownHook

您通常会这样使用它:

Runtime.addShutdownHook(new Thread() {
    public void run() {
        // do your clean up here.
    }
});

Take a look at Runtime.addShutdownHook.

You would typically use it as so:

Runtime.addShutdownHook(new Thread() {
    public void run() {
        // do your clean up here.
    }
});
夜巴黎 2025-01-09 12:35:56

您可以捕获此信号并关闭资源。大多数服务不需要正常关闭,但是您写入的文件通常需要关闭。

您可能只需要添加一个关闭挂钩即可。但我会根据你的情况对此进行测试。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文