title: SynchronizedMap ConcurrentModificationException
body: <p>I am trying to understand the SynchronizedMap and I ran the below code. I get the below Output with an exception. According to my understanding the exception is caused when the get() methods are trying to access the syncmap when a thread is still executing a write on the map or Thread is in the Sleep state. Is my understanding correct or am I missing something ?</p>
  
  <pre><code>class MapHelper1 implements Runnable {
  Map&lt;String, Integer&gt; map;
  
  public MapHelper1(Map&lt;String, Integer&gt; map) {
      this.map = map;
      new Thread(this, "MapHelper1").start();
  }
  
  public void run() {
      map.put("One", 1);
      try {
          System.out.println("MapHelper1 sleeping");
          Thread.sleep(100);
      } catch (Exception e) {
          System.out.println(e);
      }
  
  }
  }
  
  class MapHelper2 implements Runnable { 
  Map&lt;String, Integer&gt; map;
  
  public MapHelper2(Map&lt;String, Integer&gt; map) {
      this.map = map;
      new Thread(this, "MapHelper3").start();
  }
  
  public void run() {
      map.put("two", 1);
      try {
          System.out.println("MapHelper2 sleeping");
          Thread.sleep(100);
      } catch (Exception e) {
          System.out.println(e);
      }
  
  }
  }
  
  
  class MapHelper3 implements Runnable {
  Map&lt;String, Integer&gt; map;
  
  public MapHelper3(Map&lt;String, Integer&gt; map) {
      this.map = map;
      new Thread(this, "MapHelper3").start();
  }
  
  public void run() {
      map.put("three", 1);
      try {
          System.out.println("MapHelper3 sleeping");
          Thread.sleep(100);
      } catch (Exception e) {
          System.out.println(e);
      }
  
  }
  }
  
  public class MainClass {
  
  public static void main(String[] args) {
      Map&lt;String, Integer&gt; hashMap = new HashMap&lt;&gt;();
      Map&lt;String, Integer&gt; syncMap = Collections.synchronizedMap(hashMap);
      MapHelper1 mapHelper1 = new MapHelper1(syncMap);
      MapHelper2 mapHelper2 = new MapHelper2(syncMap);
      MapHelper3 mapHelper3 = new MapHelper3(syncMap);
  
  
  
      for (Map.Entry&lt;String, Integer&gt; e : syncMap.entrySet()) {
          System.out.println(e.getKey() + "=" + e.getValue());
      }
  
  }
  
  }
  </code></pre>
  
  <p>OUTPUT:</p>
  
  <pre><code>MapHelper1 sleeping
  MapHelper2 sleeping
  MapHelper3 sleeping
  
  
  Exception in thread "main" java.util.ConcurrentModificationException
  at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1494)
  at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1527)
  at java.base/java.util.HashMap$EntryIterator.next(HashMap.java:1525)
  at MainClass.main(MainClass.java:137)
  Command exited with non-zero status 1
  </code></pre>
  
  <p>EDIT : I ran the code again a few times when the output was generated without exception. Why is this behavior?</p>