Monday, 29 June 2015

Write a Singleton Example -Thread Safe ?

/*Singelton Example using Double checked (Thread Safe)*/
public class MySingleton {
 private static volatile MySingleton obj;

 //private constructor

 private MySingleton()
 {
 
 }

 //Instance method
    public static MySingleton getInstance()
    {
     if(obj==null)  //single checked
     {
      synchronized(MySingleton.class)
      {
       if(obj==null) //double checked
       {
          obj=new MySingleton();
          }
      }
     }
     return obj;
    }
    
    public void print()
    {
     System.out.println("this is my Singleton Example");
    }
    
    public void main(String args[])
    {
     MySingleton m=MySingleton.getInstance();
     m.print();
    }
}


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...