Within the main() of my application I have the following code to back up data so it doesn't get lost in the event of a system shut down.
//add hook to trigger Production Shutdown sequence
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
Production.shutdown();
}
}));
However, whether I press the Stop
button in my IDE or rely on input via the log (code shown below) it never seems to save data to the database or write any logs to the console.
ctx.deploy(server);
server.start();
//start the production process
Production.init();
System.in.read();
server.stop();
How come this shutdown function is not being executed?
From the surface, using a shutdown hook is downright straightforward. All we have to do is simply write a class that extends the java. lang. Thread class, and provide the logic that we want to perform when the VM is shutting down, inside the public void run() method.
The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown 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 exit (equivalently, System.exit) method is invoked, or.
You need to use the Exit
button, not Stop
, see my answer here for more details.
Note that this feature is currently available only in Run mode, not in Debug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With