JAVA: Executing Code Before Shutdown
Sometimes, you need to do something before application is shutting down, such as closing any open connection, closing up all opened file or anything else. Luckily, the JVM is always do these two steps below before shutdown:
- Run all registered shutdown hooks, if any. Shutdown hooks are threads registered with the Runtime. All shutdown hooks are run concurrently until they finish.
- Calls all uninvoked finalizers, if appropriate
Now we can use shutdown hooks to cleanup any resources or do something when application shutdown.
The example application is the TimePrint class. This application will print the current time on the console each second.
//TimePrint.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimePrint implements Runnable {
private SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");
public void run() {
while(true) {
System.out.println( fmt.format(new Date()) );
try {
Thread.sleep(1000);
} catch(InterruptedException ex)
{}
}
}
public static void main(String[] args) {
TimePrint obj = new TimePrint();
new Thread(obj).start();
}
}
There, you done. Just compile and run the application. The output will be like this:
2009-09-12 12:31:20 003 2009-09-12 12:31:21 018 2009-09-12 12:31:22 019 2009-09-12 12:31:23 020 2009-09-12 12:31:24 021 2009-09-12 12:31:25 023 2009-09-12 12:31:26 024
Now all we do, is add the ShutdownHook using the addShutdownHook of the Runtime class. and print Counter. It will be like this
//TimePrint2.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimePrint2 implements Runnable {
private SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");
private int printCount;
public void doPrintCount() {
System.out.println( "Printing time for " + printCount + " times" );
}
public void run() {
while(true) {
System.out.println( fmt.format(new Date()) );
//increase printCount
printCount++;
try {
Thread.sleep(1000);
} catch(InterruptedException ex)
{}
}
}
public static void main(String[] args) {
final TimePrint2 obj = new TimePrint2();
Runtime.getRuntime().addShutdownHook( new Thread() {
public void run() {
//print how many times
obj.doPrintCount();
}
} );
new Thread( obj ).start();
}
}
Run it and press CTRL+C after a couple times of print. It should print the printCount var.
Have fun with Java
0 Comments