Receive Java Process Completion Notification

There is a Java console application that should work until it is stopped using Ctrl + C or closing the console window. How can this application be programmed to perform code cleanup before exiting?

+6
java
source share
4 answers

You can use Shutdown Hook .

Basically, you need to create a Thread that will perform your shutdown actions, and then add it as a shutdown. For example:

class ShutdownHook extends Thread { public void run() { // perform shutdown actions } } // Then, somewhere in your code Runtime.getRuntime().addShutdownHook(new ShutdownHook()) 
+13
source share

Shutting down is the way to go, but keep in mind that there is no guarantee that the code is actually executed. JVM crashes, power failures, or a simple “kill -9” on your JVM can prevent code flushing. Therefore, you must make sure that your program remains in a stable state, even if it was interrupted abruptly.

Personally, I just use the database for all storage states. The transaction model ensures that persistent storage is in good condition no matter what happens. They spend years making this code flawless, so why should I spend my time on problems that have already been resolved.

+1
source share

The program to delete the temporary bat.bat file when exiting the program:

 public class Backup { public static void createBackup(String s) { try{ String fileName ="C:\\bat"+ ".bat"; FileWriter writer=new FileWriter(fileName); String batquery="cd C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin" + "\nmysqldump -uroot -proot bankdb > \""+s+".sql\"" +"\nexit"; writer.append(batquery); writer.close(); } catch(Exception e){e.getMessage();} try{ Process p =Runtime.getRuntime().exec("cmd /c start C:\\bat.bat"); } catch(Exception e){e.getMessage();} ShutDownHook sdh=new ShutDownHook(); Runtime.getRuntime().addShutdownHook(sdh); } } class ShutDownHook extends Thread { public void run() { try { File f=new File("c:/bat.bat"); f.delete(); } catch(Exception e){e.getMessage();} } } 
+1
source share

Code written inside the Thread run() method will execute when the runtime object completes ...

 class ShutdownHookclass extends Thread { public void run() { // perform shutdown actions } } //could be written anywhere in your code Runtime.getRuntime().addShutdownHook(new ShutdownHookclass()) 
0
source share

All Articles