Search code examples
javaapplication-shutdown

Java equivalent of .NET's Environment.HasShutdownStarted


In .NET, you can check the Environment.HasShutdownStarted property to see whether your service is being unloaded for whatever reason, and perform graceful unloading/cleanup.

So instead of:

while (true) { }

...you can use...

while (!Environment.HasShutdownStarted) { }

Is there an equivalent thing in Java?


Solution

  • Perhaps you're looking for a shutdown hook? This allows you to specify a thread to be run when the application is closed (as long as it's not brutally forced closed with kill -9 or similar, but in that case no environment can guarantee to do anything on shutdown.)

    Runtime.getRuntime().addShutdownHook(new Thread() {
    
        public void run() {
            //Code here.
        }
    });
    

    From a practical perspective, you should also make these threads quick to execute - since otherwise the application will appear to hang upon exiting, and no-one likes that (plus, the OS or user may choose to kill off the application, aborting the hook at an arbitrary point.)

    You can add multiple shutdown hooks, and they will be executed concurrently (and in an arbitrary order.)

    Removal of shutdown hooks can be down in a similar way by calling removeShutdownHook().