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.
1 2 3 4 5 6 7 8 9 | ... public void addShutdownHook(Thread hook) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new RuntimePermission("shutdownHooks")); } ApplicationShutdownHooks.add(hook); } ... |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | package com.turreta.demo; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.TimeUnit; public class DeamonDemo { private Closeable someResourceToCloseOnJvmExit = () -> System.out.println("Resource closed!"); public static void main(String[] args) throws InterruptedException { DeamonDemo deamonDemo = new DeamonDemo(); System.out.println("Started! Close by pressing Ctrl+C or closing the CmdLine Window!"); JVMShutdownThread jvmShutdownThread = new JVMShutdownThread(deamonDemo.someResourceToCloseOnJvmExit); Runtime.getRuntime().addShutdownHook(jvmShutdownThread); while (true) { System.out.print("."); TimeUnit.SECONDS.sleep(30); } } private static class JVMShutdownThread extends Thread { private Closeable someResourceToCloseOnJvmExit; public JVMShutdownThread(Closeable someResourceToCloseOnJvmExit) { this.someResourceToCloseOnJvmExit = someResourceToCloseOnJvmExit; } public void run() { try { this.someResourceToCloseOnJvmExit.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
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.