Class Shared{
public void sharedMethod(Object o){
//does something to Object
}
}
//this is how threads call the shared method
run(){
sharedInstance.sharedMethod(someObject);
}
Now the o
is being passed as the parameter to the method. And the same method is being called by multiple threads in parallel. Can we safely say that this code is thread safe?
There are two scenarios:
- If the
someObject
is being shared among the threads - If every Thread has its own copy of
someObject
No you cannot say that. Method parameters are local to threads, meaning each one has their own copy of the
o
reference variable, But if you call this method with the same object from multiple threads, then the argument will be shared between them (remember that Java is pass-by-value). In that case, you need to provide explicit synchronization to avoid troubles.