I’ve got a question regarding multiple-thread method invocation in Java. Let’s say we have a singleton object, and its class declared as follows:
public class SomeClass {
public void someMethod(SomeValueObject object) {
if (object.condition1) {
...
}
if (object.condition2) {
...
}
if (object.condition3) {
...
}
}
}
I’m wondering if this singleton object is being concurrently accessed and its someMethod called with distinct SomeValueObject instances, is there a chance some random thread change the reference of object for another thread’s method invocation and mess up things? And what about fields created inside method scope?
What I’m not aware of, is there any separate Method context being created for every thread invoking the method, or Method context is the same for all threads invoking it? If it is the latter case, I guess I need the synchronized keyword for thread safety, or use distinct SomeClass instances for every thread (in case I need faster execution over memory optimization). Would you please explain the matter for me?
P.S. Thanks for all of your answers guys!
If everything is local, your method is thread-safe as is. Each thread will have its own object argument on the stack, and they won’t interfere with each other.
You could have concurrency problems if two threads invoke this method with the same object as argument, or if two of those objects share some state, but that’s not the problem of the singleton. It’s the problem of the shared state, which must be properly synchronized.
Good rule of thumb: a stateless object is thread-safe. An object with immutable state is thread-safe. An object with mutable state is not thread-safe if it doesn’t properly synchronize access to the shared state.