title: Explain synchronization of collections when iterators are used?
body: <p>I understand that collections like the Hashtable are synchronized, but can someone explain to me <em>how</em> it works, and at what point(s) access is restricted to concurrent calls?  For example, let's say I use some iterators like this:</p>
  
  <pre><code>Hashtable&lt;Integer,Integer&gt; map = new Hashtable&lt;Integer,Integer&gt;();
  
  void dosomething1(){
      for (Iterator&lt;Map.Entry&lt;Integer,Integer&gt;&gt; i = map.entrySet().iterator(); i.hasNext();){
          // do something
      }
  }
  void dosomething2(){
      for (Iterator&lt;Map.Entry&lt;Integer,Integer&gt;&gt; i = map.entrySet().iterator(); i.hasNext();){
          // do something
          // and remove it
          i.remove();
      }
  }
  void putsomething(int a, int b){
      map.put(a,b);
  }
  void removesomething(int a){
      map.remove(a);
  }
  var clear(){
      map = new Hashtable&lt;Integer,Integer&gt;();
  }
  </code></pre>
  
  <p>Can someone please explain if there are any pitfalls with me calling these functions at random from different threads?  How does the iterator, in particular, do its synchronization, especially when it is using entrySet(), which would seem to also require synchronization?  What happens if clear() is called while one of the loops is in progress?  What if removesomething() removes an item that is not yet processed by a concurrent loop in dosomething1() ?</p>
  
  <p>Thanks for any help!</p>