Search code examples
multithreadingscalaakkashutdown-hook

Unregister sys.ShutdownHookThread if thread is successful?


I have a Future in Scala 2.11 that is controlled by a worker actor in Akka. The Future is executed by the worker and the worker reports back to a central actor to report success/failure and requests more work.

The futures handled by the worker are long-running and computations can take up to 15 minutes to complete depending on complexity of the task. There's a 100% chance that a deployment can happen in mid-computation, and I'm going to just let it crash. However, I do need to do some very small clean-up, so I've implemented the following sys.ShutdownHookThread in the future itself:

sys.ShutdownHookThread {
  logger.info(s"Computation was killed mid-task for user ${set.userId}. Recovering state...")
  closeProcessingState
}

My question is this: if I have registered a shutdown hook, will it unregister itself when the future is complete? Checking the API docs, the description says it is "self-unregistering" but it doesn't seem to indicate what causes it to unregister itself.

Basically, if the JVM shuts down hours later, I don't want a thousand shutdown hooks running because they didn't self-unregister.


Solution

  • The docs doesn't say it's "self-unregistering". It says: It knows how to unregister itself.. It means you can call the method remove in the instance of ShutdownHookThread.

    This ShutdownHookThread is just a helper for java.lang.Runtime#addShutdownHook. Have a look at the implementation it's quite simple.

    In other words, you are responsible for unregistering it.