Windows上的Java关闭挂钩调用关闭 [英] Java shutdown hook call on windows shut down

查看:123
本文介绍了Windows上的Java关闭挂钩调用关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,当用户通知操作系统(在我的情况下仅是Windows)关闭时,我想执行一些任务.

I have a situation in which I want to perform some task when the user signals the OS(in my case only Windows) to shutdown.

我尝试使用Java关闭钩子.我面临的问题是,当我使用System.exit(0);退出程序时,将调用关闭挂钩,但是当我直接关闭计算机时,它们却没有.

I have tried using java shutdown hooks. The problem I face is that when I exit the program using System.exit(0);, the shutdown hooks are called but when I directly shutdown the computer, they aren't.

这是我用于关机钩子的代码-

This is the code I have used for the shutdown hooks-

Runtime.getRuntime().addShutdownHook(new JVMShutdownHook()); //in main method

//within the main java class
private static class JVMShutdownHook extends Thread {
@Override
public void run() {
   //perform tasks
}
}

有什么方法可以与OS交互(我假设一些本机代码),以便它允许我的程序正常退出?

Is there any way to interact with the OS(I'm assuming some native code) so that it allows my program to exit gracefully?

任何帮助将不胜感激.

推荐答案

ShutdownHooks确实由于Windows关闭而无法正常工作.我将其视为Java的错误,并在上周打开了一个BugReport.但是,它尚未发布.

ShutdownHooks indeed do not work by shutdown of Windows. I consider it as a bug of Java and opened a BugReport last week. It has however not (yet) been published.

2008年有一个旧的错误报告: Runtime#addShutdownHook在Windows Vista上不起作用,当用户注销时. Windows 7也会发生相同的问题.票证被java.com关闭,没有令人满意的响应.

There was an old Bug Report in 2008: Runtime#addShutdownHook does not work on Windows Vista, when user logs out. The same problem occurs with Windows 7. The ticket was closed by java.com without a satifying response.

Windows通过关闭使应用程序有一些时间可以正常终止.延迟由注册表项WaitToKillApplication定义.我希望Java程序使用此延迟来执行钩子(如果设置了Runtime.runFinalizersOnExit(),则将最终确定).

Windows gives by shutdown some time to the applications to terminate gracefully. The delay is defined by the registry key WaitToKillApplication. I expect the java program uses this delay to execute the hooks (and the finalizes if Runtime.runFinalizersOnExit() is set).

让我们看看Oracle是否将其识别为错误...

Let see if Oracle recognizes it as a bug...

这篇关于Windows上的Java关闭挂钩调用关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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