Synchronised Singleton Design Pattern







 Here   i am going  to   explain  lazy  synchronized  singleton  design pattern .  If  you  go
 through the  program  you can see  it  can  be  access  globally   in multi threaded  environments.
 Here  it  is explained using   different  two way  to  get single instance .


  import  java.util.*;

/**
*   Java  synchronised singleton design Pattern 
*@author  Mukesh Jha
*
*/



public class SingletonLazy {

private static  SingletonLazy   singletonlazy ;

   private  SingletonLazy(){};
 
 /*  Lazy singleton using  double check.*/

     public void printme(){
 
   System.out.println("This  sinleton");
     }
     public static  SingletonLazy   getsingletonlazy(){
 
    if(singletonlazy==null){
 
    synchronized(SingletonLazy.class){
    if(singletonlazy==null){
       singletonlazy=new SingletonLazy();
   System.out.print("This  sinletonkk");
         }
   
         }

 
            }
   
    return  singletonlazy;
     }
 
     /* The easier way to create a thread-safe singleton class is to
   make the global access method synchronized, so that only one thread can 
     execute this method at a time. General implementation of this approach is like 
    the below class.*/



   public static synchronized SingletonLazy getInstance(){
    if(singletonlazy == null){
     singletonlazy = new SingletonLazy();
    }
    return singletonlazy;
   }


 public static void main(String args[])
 {

     SingletonLazy.getInstance().printme();
   
     singletonlazy.getsingletonlazy().printme();
   
          
 }
}

Program  Output :
This  sinleton
This  sinleton









Synchronised Singleton Design Pattern Synchronised  Singleton  Design  Pattern   Reviewed by Mukesh Jha on 1:15 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.