I've started working on an established codebase. It was set up originally to do one thing. I have been tasked with making it more generalised (by adding an extra command-line argument). My code changes have worked fine when you run the code twice, in a sequential way but when I run the code in parallel it fails miserably. The reason being, we are using Guice's @Singleton
dependency injection annotation for two key classes. These classes house a few data structures and manipulate them through the application's execution. The issue with using the singletons while running parallel is that the same object is being given to both threads and they're adding and deleting to the same data structure causing chaos and resulting in null pointers. Getting rid of the @Singleton
annotation causes issues even when running normally (without parallel threads). In the code five different objects are meant to use these singletons for some kind of functionality.
What I need is an instance of these "singleton" classes per thread that I create. Is there some way with Guice where you can replace the @Singleton
annotation with something that will inject the right instance for the thread that's using it. Keep in mind I want to keep using Guice.
I'm aware a cheap fix would be just creating an instance of these classes per thread and passing them in to each thread when they're created but it would go against the current implementation. I want to do it in a clean/automated way because I'm not sure how many threads I may be creating. So I don't want to bind different instances in a Module class because that would require me to hardcode them beforehand.
Does anyone have a solution in mind under these constraints?