Are method parameters thread safe in Java?

强颜欢笑 提交于 2019-11-28 23:38:29

问题


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

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


If you call the same method in multiple threads, and pass it the same object, that object is absolutely not safe.




回答5:


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.




回答6:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!