Java, Software Development

Java – Run Codes Before Application Shutdown

Last Updated on

This post shows how to execute codes during application shutdown possibly to clean up resources, notify remote systems or display an farewell message.

Runtime Class

The Runtime class has this addShutdownHook method that accepts a Thread object.

When an application and the JVM shutdown, the Thread object is run. A typical use-case is when we hit Ctrl+C on a running application, a System.exit(int)  is invoked, or the application crashes due to some unhandled exceptions.

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 some status that the application is still working. When we hit Ctrl+C, the JVMShutdownThread is executed just before the JVM is shutdown.

You Might Also Like