Question

I would like to create a reusable JAR that I would share across many of my projects. In this JAR, when a certain method is invoked, several threads need to be created.

I'd like to be able to add a shutdown hook (Runtime.addShutdownHook(...)) that helps these spawned threads shutdown gracefully, but not sure if I can do this from inside a "headless" (no main(String[]) method) JAR.

So I ask: can any method in any JAR access the "main" thread and add a shutdown hook to it? If so, how?

Was it helpful?

Solution

You do not need access to the main thread in order to add a shutdown hook, all you need is to have your code invoked by any thread, and for that invoked code to add the shutdown hook.

One way to achieve this is to use a static initializer block in your class. This way when you class is loaded / called the initializer will run and your shutdown hook will be added. If you have multiple classes that can be called, then you may want to create a single initializer class that all of your classes import.

Alternatively, a cleaner design might be to add the shutdown hook when you start your threads, just making sure to verify that the shutdown hook was not already added (an AtomicBoolean should be sufficient to use as a check) since you do not want to create a memory leak.

OTHER TIPS

There are no restrictions to what is allowed to add a shutdown hook so it should work the way you intend. The only restriction could be a SecurityManager which prevents your code from inserting the hook. So make sure that your projects either don't use a SecurityManager or your code has the permission to add the hook.

Be aware, that when the JVM is killed, your shutdown hook might not run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top