title: Java multi-threading atomic reference assignment
body: <p>I have a cache which I implemented using a simeple HashMap. like -</p>
  
  <pre><code>HashMap&lt;String,String&gt; cache = new HashMap&lt;String,String&gt;();
  </code></pre>
  
  <p>This cache is used most of the time to read values from it. I have another method which reloads the cache and inside of this method I basically create a new cache and then assign the reference. As I understand assignment of object reference is Atomic in Java.</p>
  
  <pre><code>public class myClass {
       private HashMap&lt;String,String&gt; cache = null;
      public void init() {
         refreshCache();
      }
      // this method can be called occasionally to update the cache.
      public void refreshCache() {
          HashMap&lt;String,String&gt; newcache = new HashMap&lt;String,String&gt;();
         // code to fill up the new cache
         // and then finally
         cache = newcache; //assign the old cache to the new one in Atomic way
      }
  }
  </code></pre>
  
  <p>I understand that if I do not declare cache as volatile, other threads will not be able to see the changes but it is not time critical for my use case to propagate the change in cache to other threads and they can continue to work with old cache for extended time.</p>
  
  <p>Do you see any threading issue? Consider that many threads are reading from the cache and only at times the cache is reloaded.</p>
  
  <p>EDIT-
  My main confusion is I do not have to use AtomicReference here as the assignment operation itself is atomic?</p>
  
  <p>EDIT -
  I understand that to make the ordering proper, I should mark cache as volatile. 
  But If refreshCache method is marked as synchronized, I do not have to make cache as volatile, as Synchronized block will take care of ordering as well as visibility?</p>