Shutdown Hooks in Java
To those of us who write enterprise code its inevitable that we run into the problem of shutdown hooks. As fancy the name sounds this is a core Java functionality which gives us the power to execute code just before the Java process dies.
Shutdown hooks are nothing but runnables without a thread to execute them. When you add a shutdown hook in your logic all you do is write some logic in there which you hope to run during your app’s shutdown.
In my case there was a long running process in the background which was updated on our UI in a status of in progress while it was running, sometimes this would take hours and hours to run and in cases where we had to send builds these long running processes would go in a limbo state. They would show in a status of in progress to the users but were not doing anything under the hood. Hence came the use case for a shutdown hook. Whenever a build or deployment would happen these interrupted long running processes should be marked failed/interrupted automatically.
Hence our logic went in there wherein we would find these limbo state processes and mark them failed. Now how shutdown hook works in Java is an interesting thing. When you proceed with a graceful shutdown (only good way to stop and restart a Java process during deployment) the Java process waits for all the non daemon threads to execute themselves (this wait is of course a small amount of time which is configurable), if threads are still active then it interrupts all of them. Post this phase it executes all registered shutdown hooks in parallel (your logic in the shutdown hook).