Thread-safe setting of a variable (Java)?

后端 未结 5 1141
我寻月下人不归
我寻月下人不归 2020-12-11 15:59

Given the following code:

public class FooBar { 

  public static volatile ConcurrentHashMap myConfigData  = new ConcurrentHashMap();      

}

public class          


        
5条回答
  •  臣服心动
    2020-12-11 16:46

    Replacing references is safe. See Java language Specification:

    When a thread uses the value of a variable, the value it obtains is in fact a value stored into the variable by that thread or by some other thread. This is true even if the program does not contain code for proper synchronization. For example, if two threads store references to different objects into the same reference value, the variable will subsequently contain a reference to one object or the other, not a reference to some other object or a corrupted reference value. (There is a special exception for long and double values; see §17.4.)

提交回复
热议问题