title: Instance variable in a Singleton class accessed by multiple threads
body: <p>I have a singleton class:</p>
  
  <pre><code>public class School {
      private HashMap&lt;String, String&gt; students;
  
      private static School school;
  
      private School(){
          students = new HashMap&lt;String, String&gt;();   
      }
  
      public static School getInstance(){
         if(school == null){
             school = new School();
         }
         return school;
      }
  
      //Method to add student
      protected void addStudent(String id, String name){
            students.put(id,name);
      }
      //Method to remove student
      protected void removeStudent(String id){
            students.remove(id);
      }
  }
  </code></pre>
  
  <p>As you can see above, in the singleton class, I have a <code>students</code> variable (a <code>HashMap</code>), there are methods to add &amp; remove student in the class.</p>
  
  <p>In my application, there could be multiple threads using this <code>School</code> class to <code>getInstance()</code> , then adding &amp; removing student. To make the access (<strong>especially the access to</strong> <code>students</code> <strong>instance</strong>) be <strong>thread safe</strong>, I am thinking to use <code>synchorized</code> keyword for <code>getInstanc()</code> method, like: </p>
  
  <pre><code>public synchronized static School getInstance(){
         if(school == null){
             school = new School();
         }
         return school;
      }
  </code></pre>
  
  <p>But I think my trivial change only can make sure only <strong>one</strong> <code>School</code> instance be created in multi-thread environment. What else do I need to do in order to make it <strong>thread safe  for accessing the</strong> <code>students</code> <strong>instance by multiple threads as well</strong>. Any good suggestion or comment is appreicated, thanks!</p>