title: Java collections synchronization
body: <p>I want to ask for advice with synchronization of Map in Java.</p>
  
  <pre><code>public class EventManager{
  
      protected final Map&lt;Class&lt;?&gt;, Object&gt; eventList;
  
      public void register(Class&lt;?&gt; key, Object object){
          eventList.put(key, object);
      }
  
      public void read(){
         for(Class&lt;?&gt; key : eventList.keySet()){
             // Next stuff
         }
      }
  }
  </code></pre>
  
  <p>I think that both methods should be synchronized with Map as monitor, like: </p>
  
  <pre><code>public class EventManager{
  
      protected final Map&lt;Class&lt;?&gt;, Object&gt; eventList;
  
      public void register(Class&lt;?&gt; key, Object object){
          synchronized(eventList){
              eventList.put(key, object);
          }
      }
  
      public void read(){
         synchronized(eventList){
             for(Class&lt;?&gt; key : eventList.keySet()){
                 // Next stuff
             }
         }
      }
  }
  </code></pre>
  
  <p>Or is there some other way how to solve it, like:   </p>
  
  <pre><code>eventList = Collections.synchronizedMap(...);    
  eventList = new ConcurrentHashMap&lt;&gt;();
  </code></pre>
  
  <p>I need to know answer to question, that even if I use <strong>Collections.synchronizedMap</strong> or <strong>ConcurrentHashMap</strong>, I will need to synchronized both methods with map object.</p>
  
  <p>Thank you, for your advice.</p>