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.
Yes, but only in two scenarios:
- if every object you pass in the
o
parameter is immutable, - if your code guarantees that there is at most one thread working on the object referenced by
o
.
Otherwise - no, since the internal state of the object can be changed by multiple threads concurrently.
When you create a thread it will have its own stack created (method and local variables).
Two threads will have two stacks and one thread never shares its stack with any other thread.
It will not effect until you are calling this on same object.
If you call the same method in multiple threads, and pass it the same object, that object is absolutely not safe.
Treat it this way.
If your threads don't share any common resources, than it's impossible to have concurrency problems.
As much as we can tell from the information you provided, the only thing that can be shared here, is someObject
. If it's thread-safe itself, or being copied for each thread, than your code is thread safe in general, unless there are other shared resources.
Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.
EDIT
The LocalObject instance in this example is not returned from the method, nor is it passed to any other objects that are accessible from outside the sharedMethod()
method.
Each thread executing the sharedMethod()
method will make use of its own Object o
as parameter.
So, the whole method sharedMethod()
seems to be thread safe.
The only exception is of course, if one of the methods called with the Object o
as parameter, stores the Object o
instance in a way that allows access to it from other threads.
来源:https://stackoverflow.com/questions/18547636/are-method-parameters-thread-safe-in-java