Calling function when program exits in java

2020-02-17 09:46发布

I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?

I am using Java 1.5.

标签: java events
4条回答
Viruses.
2楼-- · 2020-02-17 10:27

You can add a shutdown hook to your application by doing the following:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // what you want to do
    }
}));

This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.

Please note the caveats though!

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-17 10:34

Adding a shutdown hook addShutdownHook(java.lang.Thread) is probably what you look for. There are problems with that approach, though:

  • you will lose the changes if the program aborts in an uncontrolled way (i.e. if it is killed)
  • you will lose the changes if there are errors (permission denied, disk full, network errors)

So it might be better to save settings immediately (possibly in an extra thread, to avoid waiting times).

查看更多
Bombasti
4楼-- · 2020-02-17 10:52

Are you creating a stand alone GUI app (i.e. Swing)?

If so, you should consider how you are providing options to your users how to exit the application. Namely, if there is going to be a File menu, I would expect that there will be an "Exit" menu item. Also, if the user closes the last window in the app, I would also expect it to exit the application. In both cases, it should call code that handles saving the user's preferences.

查看更多
老娘就宠你
5楼-- · 2020-02-17 10:52

Using Runtime.getRuntime().addShutdownHook() is certainly a way to do this - but if you are writing Swing applications, I strongly recommend that you take a look at JSR 296 (Swing Application Framework)

Here's a good article on the basics: http://java.sun.com/developer/technicalArticles/javase/swingappfr/.

The JSR reference implementation provides the kind of features that you are looking for at a higher level of abstraction than adding shutdown hooks.

Here is the reference implementation: https://appframework.dev.java.net/

查看更多
登录 后发表回答