Java methods that reference singleton objects at the same time
I have a question about multithreaded method calls in Java Suppose we have a singleton object whose class declaration is as follows:
public class SomeClass { public void someMethod(SomeValueObject object) { if (object.condition1) { ... } if (object.condition2) { ... } if (object.condition3) { ... } } }
I want to know if this singleton object is accessed at the same time, and its somemethod is called with different somevalueobject instances, is there a chance for some random threads to change the method call of another thread referenced by the object and mess things up? What about the fields created in the scope of the method? What I don't know is whether any separate method context is created for each thread calling the method, or whether the method context of all threads calling it is the same? In the latter case, I think I need the thread safe synchronized keyword, or use a different someclass instance for each thread (if I need faster memory optimization execution) Please explain my problem
Attachment: Thank you for all your answers!
Solution
If everything is local, then your method is thread safe Each thread has its own object parameters on the stack, which do not interfere with each other
If two threads call this method with objects with the same parameters, or two objects share some state, concurrency may occur, but this is not a singleton problem This is a shared state problem and must be synchronized correctly
Good rule of thumb: stateless objects are thread safe Objects with immutable states are thread safe If the shared state is accessed incorrectly synchronously, objects with variable state are not thread safe