An example of Java Shutdown Hook resource cleanup   #


/** * This snippet shows how to writer and register the shutdown hook with the VM. * * @author java4learners * */ public class ShutdownHookExample { /** * Main method * * @param args * @throws Exception */ public static final void main(String args[]) throws Exception { File file = new File("test.dat"); // open the file writer final FileWriter fileWriter = new FileWriter(file); // Add the shutdown hook as new java thread to the runtime. // can be added as inner class or a separate class that implements // Runnable or extends Thread Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("in : run () : shutdownHook"); // save state, resource clean,up etc. if (fileWriter != null) { try { // try to close the open file fileWriter.flush(); fileWriter.close(); System.out.println("File closed successfully"); } catch (IOException e) { System.out.println("Failed to flush/close the file :" + e.getMessage()); e.printStackTrace(); } } System.out.println("Shutdown hook completed..."); } }); // main sample code, open file and write. // once the JVM terminates, the shutdown hook, would close the file. for (int i = 0; i < 10; i++) { fileWriter.write("Line : " + i); } } }

Loading Please Wait...