title: Are final static variables thread safe in Java?
body: <p>I've read around quite a bit but haven't found a definitive answer.</p>
  
  <p>I have a class that looks like this:</p>
  
  <pre><code>    public class Foo() {
  
          private static final HashMap&lt;String, HashMap&gt; sharedData;
  
          private final HashMap myRefOfInnerHashMap;
  
          static {
             // time-consuming initialization of sharedData
             final HashMap&lt;String, String&gt; innerMap = new HashMap&lt;String, String&gt;;
             innerMap.put...
             innerMap.put...
             ...a
  
             sharedData.put(someKey, java.util.Collections.unmodifiableMap(innerMap));
          }
  
          public Foo(String key) {
              this.myRefOfInnerHashMap = sharedData.get(key);
          }
  
          public void doSomethingUseful() {
              // iterate over copy
              for (Map.Entry&lt;String, String&gt; entry : this.myRefOfInnerHashMap.entrySet()) {
                  ...
              }
          }
       }
  </code></pre>
  
  <p>And I'm wondering if it is thread safe to access sharedData from instances of Foo (as is shown in the constructor and in doSomethingUseful()). Many instances of Foo will be created in a multi-threaded environment. </p>
  
  <p>My intention is that sharedData is initialized in the static initializer and not modified thereafter (read-only).</p>
  
  <p>What I've read is that immutable objects are inherently thread safe. But I've only seen this in what seems to be the context of instance variables. Are immutable static variables thread safe?</p>
  
  <p>The other construct I found was a ConcurrentHashMap. I could make sharedData of type ConcurrentHashMap but do the HashMaps it contains also have to be of type ConcurrentHashMap? Basically..</p>
  
  <pre><code>private static final ConcurrentHashMap&lt;String, HashMap&gt; sharedData;
  </code></pre>
  
  <p>or</p>
  
  <pre><code>private static final ConcurrentHashMap&lt;String, ConcurrentHashMap&gt; sharedData;
  </code></pre>
  
  <p>Or would it be safer (yet more costly to simply clone())? </p>
  
  <pre><code>this.myCopyOfData = sharedData.get(key).clone();
  </code></pre>
  
  <p>TIA.</p>
  
  <p>(Static initializer has been edited to give more context.)</p>