title: Java synchronized block vs. Collections.synchronizedMap
body: <p>Is the following code set up to correctly synchronize the calls on <code>synchronizedMap</code>?</p>
  
  <pre><code>public class MyClass {
    private static Map&lt;String, List&lt;String&gt;&gt; synchronizedMap = Collections.synchronizedMap(new HashMap&lt;String, List&lt;String&gt;&gt;());
  
    public void doWork(String key) {
      List&lt;String&gt; values = null;
      while ((values = synchronizedMap.remove(key)) != null) {
        //do something with values
      }
    }
  
    public static void addToMap(String key, String value) {
      synchronized (synchronizedMap) {
        if (synchronizedMap.containsKey(key)) {
          synchronizedMap.get(key).add(value);
        }
        else {
          List&lt;String&gt; valuesList = new ArrayList&lt;String&gt;();
          valuesList.add(value);
          synchronizedMap.put(key, valuesList);
        }
      }
    }
  }
  </code></pre>
  
  <p>From my understanding, I need the synchronized block in <code>addToMap()</code> to prevent another thread from calling <code>remove()</code> or <code>containsKey()</code> before I get through the call to <code>put()</code> but I do not need a synchronized block in <code>doWork()</code> because another thread cannot enter the synchronized block in <code>addToMap()</code> before <code>remove()</code> returns because I created the Map originally with <code>Collections.synchronizedMap()</code>.  Is that correct?  Is there a better way to do this?</p>