title: Lazily initialize a Java map in a thread safe manner
body: <p>I need to lazily initialize a map and its contents. I have the below code till now:</p>
  
  <pre><code>class SomeClass {
      private Map&lt;String, String&gt; someMap = null;
  
      public String getValue(String key) {
          if (someMap == null) {
              synchronized(someMap) {
                  someMap = new HashMap&lt;String, String&gt;();
                  // initialize the map contents by loading some data from the database.
                  // possible for the map to be empty after this.
              }
          }
          return someMap.get(key);  // the key might not exist even after initialization
      }
  }
  </code></pre>
  
  <p>This is obviously not thread-safe as if one thread comes when <code>someMap</code> is null, goes on to initialize the field to <code>new HashMap</code> and while its still loading the data in the map, another thread does a <code>getValue</code> and doesn't get the data when one might have existed.</p>
  
  <p>How can I make sure that the data is loaded in the map only once when the first <code>getValue</code> call happens. </p>
  
  <p>Please note that it's possible that the the <code>key</code> won't exist in the map after all the initialization. Also, it's possible that the map is simply empty after all the initialization.</p>