Java, Software Development

Run Java Codes Before Application Shutdown

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

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.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like