17

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.

Ben
  • 54,723
  • 49
  • 178
  • 224

4 Answers4

44

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!

Community
  • 1
  • 1
Mat Mannion
  • 3,315
  • 2
  • 30
  • 31
  • 1
    Where should be the shutdown hook located? I have a program and I need to save some data too. I am using MVC model but I dont know where to place this hook. Thanks – frank17 Apr 10 '16 at 16:33
  • 1
    Anywhere the code gets called. I have used it in my main method and my static block and it worked equivalently. – EngineerWithJava54321 Jun 17 '16 at 15:27
  • My code runs System.exit(exit_code) in multiple locations, how do i apply this so that the shutdownhook runs no matter the exit code? (Currently i place the code in the constructor and it only runs when programs exits in main method) – kbluue Jan 03 '18 at 16:03
11

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
  • 7,168
  • 26
  • 29
0

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
  • 4,967
  • 2
  • 28
  • 35
0

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
  • 16,067
  • 8
  • 44
  • 68