I have a static function to save the high score! I wonder is there a easy way to call this function automaticlly when we exit a program. If in C++, I can put this function in destructor and it works. But in java I dont know how! Any idea to do this? Thank you!
            Asked
            
        
        
            Active
            
        
            Viewed 151 times
        
    0
            
            
        - 
                    Use Google next time. – Kon May 21 '15 at 05:12
 - 
                    And what is your program? Is it command line? Is it a GUI program? – fge May 21 '15 at 05:13
 - 
                    @Kon you probably don't want to use a JVM exit hook if you run a GUI; rather, you want to plug into the window close event. – fge May 21 '15 at 05:14
 - 
                    2@fge Mostly yes, but that won't fire if the process is terminate through a kill -9 or taskkill, for example. – Kon May 21 '15 at 05:14
 - 
                    1@Kon neither will a JVM exit hook :p – fge May 21 '15 at 05:15
 - 
                    @fge Ah, wasn't aware. That makes sense actually. But at least this case covers all GUI types as well as console programs. But a Listener would be cleaner. – Kon May 21 '15 at 05:15
 - 
                    Thanks. I will do a reseach. Its a game... – user3819845 May 21 '15 at 05:17
 
2 Answers
2
            For all kind of java applications, you could REGISTER A SHUTDOWN HOOK, like this:
   Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("Your job when app shutdown");
   }
  });
        Krzysztof Cichocki
        
- 6,294
 - 1
 - 16
 - 32
 
- 
                    
 - 
                    At the beginning of your program. It will register the hook, and it will automatically runs the code when the time comes. – Soley May 21 '15 at 05:25
 - 
                    If it works for You, then vote my post up, and mark as the right answer, so others would find this solution easier. – Krzysztof Cichocki May 21 '15 at 05:34
 
0
            
            
        for Swing GUI programs
myform.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                    // your exit codes here
                    System.exit(0);
            }
        });
        Soley
        
- 1,716
 - 1
 - 19
 - 33