How to invoke method before console program terminates itself

389 Views Asked by At

I would like to serialize some objects in console application just before program terminates itself(without adding this code simply in the end of main method)?

Is that possible to solve out?

1

There are 1 best solutions below

0
Vivek Kothari On

You can register a shutDownHook as below:

public class Task implements Runnable {
    public void run() {
        yourWork();
    }
}

public class App{
    static {
        Runtime.getRuntime().addShutDownHook(new Thread(new Task()));
    }
    public static void main(String[] args){
        .
        .
        .
    }
}