Thursday, June 20, 2013

singleton pattern

deal with multithreading:
1, synchronization: if it's used rarely in the application
public class Singleton{
  private Singleton(){}
  private static Singleton  uniqueInstance;
  public static synchronized Singleton getInstance(){
    if(uniqueInstance == null){
        uniqueInstance = new Singleton();
    }
    return uniqueInstance;
  }
 // other methods
}

2, make an eagerly created instance

public class Singleton{
  private Singleton(){}
  private static Singleton  uniqueInstance = new Singleton();
  public static  Singleton getInstance(){
    return uniqueInstance;
  }
 // other methods
}

3, double check lock

public class Singleton{
  private Singleton(){}
  private static volatile Singleton  uniqueInstance;
  public static Singleton getInstance(){
    if(uniqueInstance == null){
      synchronized(Singleton.class){
        if(uniqueInstance == null) 
          uniqueInstance = new Singleton();
       } 
    }
    return uniqueInstance;
  }
 // other methods
}

No comments:

Post a Comment