Class Shared{
public void sharedMethod(Object o){
//does something to Object
}
}
//this is how threads call the shared method
run(){
Yes, but only in two scenarios:
o
parameter is immutable,o
.Otherwise - no, since the internal state of the object can be changed by multiple threads concurrently.
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.
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.
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.
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.