开发者

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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜