1

Wondering how to programmatically access the exit status in System.exit from a shutdown hook? Different types of shutdowns need to lead to different logics in my application (how "hard" to shutdown), there's a few ways I'm thinking of doing this but this would be the simplest.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • Check this out if you're really set on accessing it from the hook: http://stackoverflow.com/questions/1486679/determine-exit-status-within-the-java-shutdown-hook-thread?rq=1 – Floegipoky Nov 14 '13 at 23:29

1 Answers1

2

Check out the question I linked if you're really set on this. However, you shouldn't need to access the code from the hook. When you set the exit code, you know exactly which "type" of shutdown you need. It's possible to dynamically specify the shutdown behavior at that time. Instead of registering your shutdown hook(s) at the beginning of execution and then doing this:

startShutdown(int code) {
    System.exit(code);
}

You could do something along these lines:

private Map<Integer, Thread> shutdownHandlerLocator; // initialize this on startup with all of the exit codes and their corresponding handlers

startShutdownTypeA(int code) {
    Runtime.getRuntime().addShutdownHook(shutdownHandlerLocator.get(code));
    System.exit(code);
}

This basic approach can be modified to fit the design needs of your project and the complexity of your teardown logic. There's opportunity to apply inheritance. You could also create a number of very small and specific hooks and register them individually depending on the behavior you need (recommended). The possibilities are really endless and without knowing the exact details of what you're trying to do it's difficult to recommend a more specific design.

Now this is all well and good, but here's the thing- teardown is supposed to be as minimal as possible, because execution is in a fairly fragile state when your shutdown hooks are running. If you're finding that you need really complicated behavior, you may want to reexamine your overall design.

I should also probably mention that there's some memory management implications in using threads in the manner above.

Floegipoky
  • 3,087
  • 1
  • 31
  • 47