Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Shutdown function not executing

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?

like image 325
Webnet Avatar asked Jun 06 '13 18:06

Webnet


People also ask

How to use shutdown hook?

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.

What is addShutdownHook method in Java?

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.


1 Answers

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.

like image 142
CrazyCoder Avatar answered Oct 19 '22 02:10

CrazyCoder