7

Within the main() of my application I have the following code to back up data so it doesn't get lost in the event of a system shut down.

    //add hook to trigger Production Shutdown sequence
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            Production.shutdown();
        }
    }));

However, whether I press the Stop button in my IDE or rely on input via the log (code shown below) it never seems to save data to the database or write any logs to the console.

    ctx.deploy(server);

    server.start();

    //start the production process
    Production.init();

    System.in.read();
    server.stop();

How come this shutdown function is not being executed?

Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    Is there code that calls `System.exit` when a shutdown happens? If you're having trouble finding any, maybe install a security manager that logs attempts to exit. – Mike Samuel Jun 06 '13 at 18:41
  • Why don't you shutdown() at the end of `main()` instead? – fge Jun 06 '13 at 18:42
  • @fge There could be multiple threads besides `main`. If there are, the program will shutdown while the other threads are doing other stuff, causing problems. – gparyani Jun 06 '13 at 18:43
  • @gparyani sure, this can happen if you lose the reference to what you want to shut down in main, but if you do so I'd question your sanity ;) – fge Jun 06 '13 at 18:45

2 Answers2

13

You need to use the Exit button, not Stop, see my answer here for more details.

Note that this feature is currently available only in Run mode, not in Debug.

Community
  • 1
  • 1
CrazyCoder
  • 389,263
  • 172
  • 990
  • 904
  • 1
    Just today I found about stop button ignoring shutdown hooks as well. Personally I think it's a very bad decision, I always thought Stop button simulates Ctrl+C (that is SIGINT on unix). And then there is debug without that Exit button. You can try to kill process knowing its PID (`jps` can help), right? Wrong... Using Windows and its `taskkill` process cannot be stopped in normal way - only forcefully (`taskkill /f /pid x`) - it seems IDE is somehow "protecting" it (both in debug and normal run). This doesn't make testing of shutdown hooks any easier. Debugging just plain impossible. – virgo47 Nov 24 '14 at 17:41
0
System.exit(0)

add this line in your code. Debug from here onwards