You'll have to register a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
// do your thing
}
}));
Note that this will only get executed if the program ends naturally.