Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are method parameters thread safe in Java?

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
like image 675
Narendra Pathai Avatar asked Aug 31 '13 11:08

Narendra Pathai


People also ask

Are method variables thread-safe in Java?

On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.

How do I know if a method is thread-safe?

To test if the combination of two methods, a and b, is thread-safe, call them from two different threads. Put the complete test in a while loop iterating over all thread interleavings with the help from the class AllInterleavings from vmlens. Test if the result is either an after b or b after a.

Are final variables thread-safe?

Final variables are immutable references, so a variable declared final is safe to access from multiple threads. You can only read the variable, not write it.

What is not thread-safe in Java?

The decrement method is not static and will synchronize on the instance used to call it. I.e., they will synchronize on different objects and thus two different threads can execute the methods at the same time. Since the ++ and -- operations are not atomic the class is not thread safe.


1 Answers

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.

like image 189
MD Sayem Ahmed Avatar answered Sep 25 '22 06:09

MD Sayem Ahmed