Are method parameters thread safe in Java?

前端 未结 6 1746
-上瘾入骨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.

提交回复
热议问题