Nick Heiner
Nick Heiner

Reputation: 122570

Java: Take action on process death?

I am debugging a Java app, which frequently involves killing the process. I would like to do some cleanup before the app dies. Is there a way to catch the event and react accordingly? (Sort of like catching a KeyboardInterrupt in Python.

Update: I tried adding this to main(), but it doesn't seem to be working:

Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Closing...");
            }
        });

The code does not get run.

Upvotes: 0

Views: 762

Answers (2)

developmentalinsanity
developmentalinsanity

Reputation: 6249

If you're stopping the process via the "stop" button in Eclipse, then shutdown hook won't run. As far as I'm aware, there isn't any way to run a hook in that scenario - it pretty much kills the JVM with no chance for cleanup. If you were running from the commandline, CTRL+C would work, but I don't think you can do that from in eclipse very well.

UGLY HACK:

Add something like this at the start of main:

    JFrame killer = new JFrame("Killer");
    killer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    killer.setSize(100, 100);
    killer.setVisible(true);

Closing the resulting window will trigger a System.exit(), which should allow shutdown hooks to run. Of course, this won't work if the program is suspended in the debugger. YMMV.

Upvotes: 2

darioo
darioo

Reputation: 47193

You can try using a shutdown hook.

Be aware that this doesn't guarantee your hook will be called, so there is no bulletproof way to be 100% sure your cleanup will be actually done.

There is a limited timeframe when the JVM can do cleanup, and if you attempt to do too much in the hook, don't expect it will be done.

Upvotes: 0

Related Questions