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.