gpt4 book ai didi

java - 如何在程序结束时关闭数据库连接?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:09:23 25 4
gpt4 key购买 nike

在 Java 程序中,我有一个保存数据库连接的单例类,整个程序都使用它。

程序结束时如何告诉Java关闭连接?

我可以在 main 的末尾放置一个 connection.close() 语句,但如果程序意外结束,例如未捕获的异常或程序中某处的“exit”调用,则不会执行该语句。无论程序如何结束,我如何告诉 Java 关闭连接?

最佳答案

你可以使用 a VM shutdown hook如果方法 System.exit 可能被调用。

Runtime.getRuntime().addShutdownHook(new Thread(() -> closeDatabaseConnection()));

如果程序正常退出,也会调用关闭 Hook :

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the System.exit method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

但如果发生意外情况,不能保证它们会运行:

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.

关于java - 如何在程序结束时关闭数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48110807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com