title: An Object reference return from a Singleton Class is Thread safe?
body: <p>I want to return an object from a singleton class, that object is using by many threads and also two methods in the singleton class. Is it safe to return that object reference? Please see my sample</p>
  
  <pre><code>public class MainClass {
      public static void main(String[] args) {
          Thread t = new Thread() {
              public void run() {
                  MyObject rv = Singleton.getInstance().get();
  
                  for (int i = 0; i &lt; 100; i++) {
                      System.out.println("THREAD 0 : " + rv.getCount());
                  }
              }
          };
          t.start();
  
          Thread t1 = new Thread() {
              public void run() {
                  for (int i = 0; i &lt; 100; i++) {
                      Singleton.getInstance().update();
                  }
              }
          };
          t1.start();
      }
  }    
  </code></pre>
  
  <p>and</p>
  
  <pre><code>import java.util.HashMap;
  
  public class Singleton {
      private static Singleton instance;
  
      private Singleton() {
          MyObject rv = new MyObject(1, 1);
          hashmap.put(1, rv);
      }
  
      public static synchronized Singleton getInstance() {
          if (instance == null) {
              instance = new Singleton();
          }
          return instance;
      }
  
      private final HashMap&lt;Integer, MyObject&gt; hashmap = new HashMap&lt;&gt;();
  
      public MyObject get() {
  
          return hashmap.get(1);
      }
  
      public void update() {
          hashmap.get(1).setCount(hashmap.get(1).getCount() + 1);
      }
  }     
  </code></pre>
  
  <p>and</p>
  
  <pre><code>public class MyObject {
      int count;
      int id;
  
      MyObject(int id, int count) {
          this.id = id;
          this.count = count;
      }
  
      public int getCount() {
          return count;
      }
  
      public void setCount(int count) {
          this.count = count;
      }
  
      public int getId() {
          return id;
      }
  
      public void setId(int id) {
          this.id = id;
      }
  }
  </code></pre>