Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with badly behaved libraries that don't stop threads

What are some workarounds when dealing with third party libraries that don't correctly clean-up threads when the library is shutdown?

Many libraries expose lifecycle methods, either explicitly or implicitly, for the code contained therein. For example, a web application framework exists within a web application context in a servlet container. When the context is created, the framework may start some threads, for various reasons.

Now, taking the example further, when the servlet container or the web application context is shutdown, the web application framework should terminate all these threads. Either the ExecutorServices created by the library should be shutdown, or some other means of stopping those threads should be enacted.

Worst case is that the threads are non-daemon threads. These would actually stop the termination of the Java process. But even if they are daemon threads, allowing threads to continue is probably bad practice. If (back to the example) the servlet container is embedded within other code that other code may continue to run with the threads still chugging away, which may cause problems.

There's no programmatic way exposed to stop these threads, so what can be done?

If you are using such a third party library, what are the ways to force existing threads to be shutdown?

like image 326
Dan Gravell Avatar asked Aug 10 '12 13:08

Dan Gravell


1 Answers

If you are using such a third party library, what are the ways to force existing threads to be shutdown?

In general, there is no safe way to do this that is guaranteed to work in all cases. The closest you are likely to get to a safe solution is to use the ThreadGroup to enumerate all existing Threads, and use Thread.interrupt() to tell each thread to go stop. Of course, there is no guarantee that the threads will pay attention, or that they will shutdown cleanly in response to an interrupt.

IMO, the best strategy is:

  • if the threads do not need to be shut down cleanly, then pull the plug on the JVM by calling System.exit()

  • if the threads need to be shut down cleanly to avoid the possibility of damage, then don't use the library ... or fix the problem yourself.

like image 183
Stephen C Avatar answered Sep 28 '22 04:09

Stephen C