Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a thread upon app unload

Tags:

I maintain a library that starts a daemon thread to do work in the background. In regular Java and Android applications, this thread is started once and runs for the lifetime of the process. It never exits and that's okay.

When my library is included in an application container that supports application unloading (such as Tomcat), the application never unloads. My running thread holds strong references to its own class and that prevents the entire application from being unloaded. Users of my library cannot hot-swap their app without leaking memory each time.

What's the best way to get signaled when the application container wishes to unload my library?

This is a small library without any dependency on application container APIs. It doesn't know which application container it's running in and it doesn't want to!

The fact that this library starts a thread is an implementation detail. End users of the library shouldn't have to know that a thread is being started, and it is not their responsibility to shut it down.

like image 820
Jesse Wilson Avatar asked Feb 09 '15 05:02

Jesse Wilson


1 Answers

Your best bet is to provide a method to clean up the library. The end user will have to call it (presumably based on handling application lifecycle in the container). You could also provide a Listener for those cases when it is used in a compatible servlet container (e.g., Tomcat), but your end user will still have to be aware and put the descriptor in the web.xml.

The only other alternative is that your end user is going to have to create a Listener that manages to get the thread to die. I have had to do this on several occasions and it is not pretty. It usually involves using reflection to get ahold of the thread and killing it. Of course, the ThreadDeath exception is handled by some libraries and the threads refuse to die. This then requires more significant use of reflection to clean up the mess.

Your end users are much better off if you give them an easy way to clean up the library. It sucks that they have to know about your implementation details, but they already do because you are keeping the app from unloading.

like image 108
Rob Avatar answered Sep 17 '22 18:09

Rob