Java shutdown hook call on windows shut down

若如初见. 提交于 2019-12-11 03:55:43

问题


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.

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
}
}

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

Any help would be greatly appreciated.


回答1:


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.

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 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).

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




回答2:


You will have to write native methods. Two for adding and removing your shutdown hook, and one that will act as a callback method for the hook, from where java code will be invoked. You hook will have to listen for OS shutting down message and invoke your callback when this occure. This is the way that plenty of apps that prevents windows from going into sleep mode or running screen saver works.

Check for some information about JNI here

http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html

and about hooks here

https://msdn.microsoft.com/en-us/library/windows/desktop/ms644960%28v=vs.85%29.aspx



来源:https://stackoverflow.com/questions/29179684/java-shutdown-hook-call-on-windows-shut-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!