Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java shutdown hook call on windows shut down

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.

like image 276
Pranav Avatar asked Nov 21 '25 20:11

Pranav


1 Answers

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

like image 113
Olivier Faucheux Avatar answered Nov 23 '25 10:11

Olivier Faucheux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!