So I have a Singleton class and in it a non-static public method that is called by multiple threads. In the non-static method I have local references to objects created by a Stored Procedure which I surmise means the ‘new’ keyword gets called somewhere.
1 public void someMethod(SomeObjectParameter parameter) {
2
3 Thing thingOne = synchornizedStoredProcedureCall():
4 doSomethingWith(thingOne);
5 doSomethingElseWith(thingOne);
6
7 }
Currently lines 3 through 5 are in a synchronized code block which I would like to reduce down to just having the stored procedure call as synchronized.
So… Say we have two threads, Thread1 and Thread2. Thread1 is about to execute line 3 and Thread2 is about to execute line 4. Since this is a local reference, will each thread maintain a different reference or will synchornizedStoredProcedureCall overwrite the reference to thingOne as doSomethingWith is about to use it?
What if thingOne is declared final or if I made it immutable?
The different threads have different stacks. The
thingOneis stored in the per-thread stack so cannot be overwritten by the other thread. You also need to make sure that thesynchornizedStoredProcedureCall()is returning a different instance ofThingeach time and not astaticor instance variable. Both threads need to be working on differentThinginstances.As long as the
doSomethingWith(...)anddoSomethingElseWith(...)calls are thread safe and only work withthingOneargument and constants (etc), protecting just thesynchornizedStoredProcedureCall()should be fine.As @Marko points out, without seeing the
Thingclass, we cannot be guaranteed that it is thread-safe and not storing internal state.