0

Java – Run Codes Before Application Shutdown

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 is shutdown, the Thread object is ran. 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.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert