Java, Software Development

Run Java Codes Before Application Shutdown

This post shows how to run Java codes before an application shutdown. We can use this idea to clean up resources, notify remote systems or display a farewell message before the application completes its execution or terminates.

Java Runtime Class And Its Before Shutdown Hooks

The Runtime class has an addShutdownHook method that accepts a Thread object. For instance, consider the following sample codes. We can override it. First, we get a SecurityManager object. Then, we check if we can proceed. Otherwise, we return an error. Next, we add the Thread object to the shutdown hook, and our codes are within that Thread object.

When an application and the JVM shut down, Java runs the Thread object. A typical use-case would be when we hit Ctrl+C on a running application; some codes run System.exit(int), or the application crashes due to runtime errors.

Java Command Line Application Codes

When we run the codes in the command line window and wait for a few minutes, dots are printed out to indicate that the application is still working. When we hit Ctrl+C, the JVMShutdownThread is executed just before the JVM is shutdown.

And that’s how we can run Java codes before the application shutdown!

This post is part of a reboot Java tutorial.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like