Java程序异常退出的处理
假设我有一个打开数据库连接的 Java 应用程序。 通常我会在finally块中添加一个connection.close(),但是在kill操作或任何其他异常终止的情况下该块不会被执行,不是吗? 作为一名程序员,我是否可以采取任何其他预防措施,以便在应用程序退出之前正确关闭连接?
Suppose I have a Java application that opens a database connection. Normally I would add a connection.close() in a finally block, but this block wouldn't be executed in the case of a kill operation, or any other abnormal termination, would it? Are there any other precautions that I, as a programmer, can make in order to close the connection properly before the application exits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该查看 Java 的 Runtime.addShutdownHook() 方法 (http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)) 。 它允许您添加一个钩子,该钩子将在虚拟机终止时被调用。 您可以使用它来调用清理例程。
不过,这适用于 TERM 信号。 KILL 信号将终止进程,并且不允许它进行任何清理(因为接收进程无法捕获或忽略 KILL 信号)。
You should look at the Runtime.addShutdownHook() method for Java (http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). It allows you to add a hook that will be called when the virtual machine terminates. You can use it to call a cleanup routine.
That would be for a TERM signal though. A KILL signal will kill the process and not allow it to do any cleanup (because the KILL signal cannot be caught or ignored by the receiving process).
如果外部的东西杀死了你的程序,你就无能为力。 显然他们想要阻止,那你怎么阻止他们呢?
我打算建议 关闭钩子,但 Javadocs 声明:
(强调我的)
If something external kills your program, there's nothing you can do about it. Obviously they wanted to stop it, so how can you prevent them?
I was going to suggest a shutdown hook, but the Javadocs state:
(emphasis mine)
终止程序最终会使从程序到
[Oracle|SQL Server|MySQL|PostgreSQL]
服务器的TCP
流超时。服务器将看到它并回滚任何挂起的事务。
Killing a program will eventually timeout a
TCP
stream from your program to your[Oracle|SQL Server|MySQL|PostgreSQL]
server.The server will see it and rollback any pending transactions.
当你真的被杀死时(UNIX 上的
kill -9
),你无能为力。finally
-block 是您最多可以做的,请参阅SO:在 Java 中,是否保证调用“finally”块(在主方法中)? 了解详细信息。When you really get killed (
kill -9
on UNIX), you can not do anything against that.A
finally
-block is the most you can do, see SO: In Java, is the “finally” block guaranteed to be called (in the main method)? for details.某种程度的异常终止是不可避免的。 您如何捕获服务器电源线被拉动的事件?
Some level of abnormal termination is unavoidable. How would you catch the event of the power cable being pulled on the server?