Java shutdown hook not working on system shutdown

154 views Asked by At

I am working on a JavaFX application that is to be run in background in most of time. So i need to execute code if a user close the application. But most of the time application will run in background/system tray so user may be forgot to close the application. So I need to hit the URL if user shutdown or restart the computer. After research I found Shutdown hook in java that can be used to excute task before JVM shutdown, so I implemented the Shutdown hook. When I tested it, it is working if i am closing the application, but not working if I shutdown the system.

Child class

public class ShutDownTask extends Thread {
    CheckInPageController controller = new CheckInPageController();
    @Override
    public void run() {
        System.out.println("ShutDown Called");
        System.out.println("Performing shutdown");
        //Hitting a URL here
            controller.checkoutRequest();

    }
}

Main class

    public static void main(String[] args) throws InterruptedException, IOException {
        launch(args);
                ShutDownTask task = new ShutDownTask();
        // add shutdown hook
        Runtime.getRuntime().addShutdownHook(task);
        // exit application
        System.exit(0);
    }

Please give me solution of it or tell me why is this happening Thanks in advance

1

There are 1 answers

0
JonathanDavidArndt On

As noted in the comments, using a shutdown hook can be a handy way to perform non-essential tasks, but -- by its very nature -- cannot be relied upon.

This is not limited to Java -- C/C++ has a finalize function which is run when an object is garbage collected. This can be helpful in optimizing some tasks, but there is no guarantee it will ever be called.

One need not look far for ways an application might not shutdown properly: power failure, an uncaught exception or out-of-memory error, even an OS crash will happen sooner rather than later.

The heartbeat suggestion is excellent: while the shutdown routine is not guaranteed, your application will startup again eventually (provided you or someone else is still wants to use it!) Check the previous state that was saved in the heartbeat and take any necessary action during startup.