I am currently refactoring the server side of an existing project.
We are using now guice to bind the specific modules and its objects.
Over the last 2 weeks we often have a problem which looks like that guice is mixing up some of the used object instances.
The problem is a class which is reponsible for building up a String which will be inserted in a database. This class is used from a rpc service which can be called quite fast in a row. So what happens is that RPC service 1 calls this class and in the meantime RPC service 2 is calling this class as well and changing the global parameter which are used for string building. The builder class is kind of stupid as it takes a param from a method sets some parts of the param as global variables and processes the string.
I think the main problem are the global variables but I dont know how I could get rid of them in an elegant way. They are used in all other methods which are called from the init method(e.g. startMethod() calls buildStringOne(), buildStringTwo() and those are accessing both global variables which are set in startMethod()).
Is there a better way how I could bind this object or do I need to remove the global variables and provide them as paramter in the other methods?
Thanks for your help.
Using shared mutable state is asking for trouble. It sounds like your root problem is really a thread safety issue. However, you don’t have to solve thread safety issues by making mutable state thread safe — you can also just make it so the state is only visible to one thread.
You may be able to use Guice’s request-scoped objects to solve this problem. If the troublesome class can be used in such a way that it’s injected, Guice will provide a new instance for each servlet request. If you’re using it in classes with longer scope than Request (such as Singleton), inject a Provider. Calling get() will return the appropriate Foo instance for the request that the calling thread is handling.
See https://code.google.com/p/google-guice/wiki/ServletModule#Using_RequestScope for more.