Are method parameters thread safe in Java?

前端 未结 6 1747
-上瘾入骨i
-上瘾入骨i 2020-12-14 03:24
Class Shared{    
     public void sharedMethod(Object o){
          //does something to Object
     }     
}

//this is how threads call the shared method
run(){
           


        
相关标签:
6条回答
  • 2020-12-14 03:50

    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.

    0 讨论(0)
  • 2020-12-14 03:51

    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.

    0 讨论(0)
  • 2020-12-14 03:58

    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.

    0 讨论(0)
  • 2020-12-14 04:07

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

    0 讨论(0)
  • 2020-12-14 04:07

    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.

    0 讨论(0)
  • 2020-12-14 04:13

    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.

    0 讨论(0)
提交回复
热议问题