tags:

views:

846

answers:

4

Hi

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

I am using java 1.5.

+7  A: 

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!

Mat Mannion
+1  A: 

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).

mfx
A: 

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.

Avrom
A: 

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/

Kevin Day