title: Correct use of Singleton Pattern
body: <p>I am trying to implement an example of the singleton pattern. One of our questions is to run two threads each calling getInstance() and to verify only one instance of the Singleton object was created. </p>
  
  <p>Here is my Singleton code;</p>
  
  <pre><code>public class OurSingleton {
  
      static OurSingleton ourSingleton;
      static int instanceCounter;
  
      private OurSingleton(){
          instanceCounter++;
      }
  
      public static synchronized OurSingleton GetSingletonInstance(){
  
          if( ourSingleton == null){
  
              ourSingleton = new OurSingleton();
  
          }
          return ourSingleton;    
      }
  
      public static int getCounter() {
  
          return instanceCounter;
  
      }
  }
  </code></pre>
  
  <p>And my main;</p>
  
  <pre><code>public class Main {
  
      /**
       * @param args
       */
      public static void main(String[] args) {
  
          OurSingleton mySingleton = null;
  
          Thread one = new Thread(new GetSingletonInstance(mySingleton));
          Thread two = new Thread(new GetSingletonInstance(mySingleton));
  
          one.start();
          two.start();
  
  
          System.out.println("Main: " + mySingleton.getCounter());
      }   
  }
  
  class GetSingletonInstance implements Runnable {
  
      int count = 0;
      OurSingleton singleton;
  
      public GetSingletonInstance(OurSingleton ourSingleton){
          singleton = ourSingleton;
      }
  
      @Override
      public void run() {
          try {
              while (count &lt; 5000000) {
                  singleton.getSingletonInstance();
                  count++;    
              }
  
          } catch (Exception e) {
  
              e.printStackTrace();
          }
  
          System.out.println("Thread: " + singleton.getCounter());
  
      }       
  }
  </code></pre>
  
  <p>When I run this code I get the following output;</p>
  
  <blockquote>
    <p>Main: 0 Thread: 1 Thread: 1</p>
  </blockquote>
  
  <p>Can somebody explain the reason for this output? I thought only a single instance of Singleton existed across the board. Does this mean another object is being created in the threads ?? Any advice is appreciated !</p>