[ACCEPTED]-Calling function when program exits in java-events

Accepted answer
Score: 43

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

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

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

Please 1 note the caveats though!

Score: 11

Adding a shutdown hook addShutdownHook(java.lang.Thread) is probably what 4 you look for. There are problems with that 3 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 2 save settings immediately (possibly in an 1 extra thread, to avoid waiting times).

Score: 0

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

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

Score: 0

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

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

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

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

More Related questions