Search code examples
javamultithreadingprocessisolation

Thread isolation in Java


Is there any sure-fire way to ensure threads remain isolated from one another, in Java? I've had an issue for a week and a half, where threads implementing various 3rd party source code keep colliding due to static variables and other such things that are really beyond my control.

I know a single system can run as many instances of the project I'm working on, as it wants. But when trying to incorporate everything into a threaded, single executable, there are always errors and exceptions.

I'm almost at the point of just launching a new process for each instance of this program that I want, but I'd really rather not go down this route (it would eliminate a lot of real-time data I gather, as well as hinder my ability to kill a targeted process).

Suggestions? Thanks!


Solution

  • If the authors of the library you want to use have not designed their code to be thread safe, then there's little you can easily do except to prevent two of your threads calling it at the same time.

    You can pull some tricks with classloaders, but this tends to lead to a whole new world of complexity. To elaborate, it's possible to load the same class twice (or more times) into the same JVM, if you use different classloaders - hence you could effectively get independent copies of static variables. This use of separate classloaders is exploited by some Java EE Application Servers. That in turn leads to questions of which classloader and classpath gets used when the libraries themselves start to do some reflection and dynamic classloading. I would not recommend this approach unless your need is very great.

    By preferences would be:

    1). Have a single-threaded worker for the unsafe code. Try to do as much work as possible out in your mulit-threaded app, dropping into the Worker as little as you can.

    2). If the worker is the major part of your processing and so you really need parallel execution pull the worker out into mulitple separate processes, use some IPC communication to share the work out. This feels like a JMS queueing solution might work nicely.

    3). If you can't afford the IPC overhead try to find a thread-safe alternative to the libraries, or if you have influence with the authors get them to fix the code. It really should not be that hard to increase their parallelism.