In Java, is it safe to change a reference to a HashMap read concurrently

前端 未结 4 983
慢半拍i
慢半拍i 2020-12-15 07:08

I hope this isn\'t too silly a question...

I have code similar to the following in my project:

public class ConfigStore {

    public static class Co         


        
4条回答
  •  温柔的废话
    2020-12-15 07:41

    Since changing references is an atomic operation, you won't end up with one thread modifying the reference, and the other seeing a garbage reference, even if you drop volatile. However, the new map may not get instantly visible for some threads, which may consequently keep reading configuration from the old map for an indefinite time (or forever). So keep volatile.

    Update

    As @BeeOnRope pointed out in a comment below, there is an even stronger reason to use volatile:

    "non-volatile writes [...] don't establish a happens-before relationship between the write and subsequent reads that see the written value. This means that a thread can see a new map published through the instance variable, but this new map hasn't been fully constructed yet. This is not intuitive, but it's a consequence of the memory model, and it happens in the real word. For an object to be safely published, it must be written to a volatile, or use a handful of other techniques.

    Since you change the value very rarely, I don't think volatile would cause any noticeable performance difference. But at any rate, correct behaviour trumps performance.

提交回复
热议问题