Saturday, November 21, 2009

Perform Shutdown Operations on Java

We could often use the finalize() method inside the class to perform shutdown operations.
We cannot be sure about the execution of finalize() method. For example if you close an application using Ctrl+C from the command line the finalize() method won't get executed.

So it will be better to add a shutdown hook to the Java runtime environment.
For example,
Runtime.getRuntime().addShutdownHook(Thread t) ;
adds a shutdown hook to the JVM and when the application exits(due to interrupt or normal termination) the runtime would call the start() method of the Thread t .

eg:
public class MainClass {
public static void main(String[] args) throws Exception {
Object f = new Object() {
public void finalize() {
System.out.println("Running finalize()");
}
};
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Running Shutdown Hook");
}
});

f = null;
System.gc();

System.out.println("Calling System.exit()");
System.exit(0);
}
}




OUTPUT

Calling System.exit()
Running finalize()
Running Shutdown Hook

No comments:

Post a Comment