Basic concepts for Computer Science

  • operating system
  • Java
  • DataBase
  • Web

Design Pattern

Singleton Pattern

  1. private constructor
  2. private static instance of the same class
  3. public static method that will return the singleton class instance variable.
// Thread unsafe
public class ASingleton {

    private static ASingleton instance = null;

    private ASingleton() {
    }

    public static ASingleton getInstance() {
        if (instance == null) {
            instance = new ASingleton();
        }
        return instance;
    }

}
// Thread Safe v1
/* Synchronize the getInstance() method
* Slow performance because of locking overhead.
* Unnecessary synchronization that is not required once the instance variable is initialized.
*/

// Thread Safe v2
/*
* Thread safety is guaranteed
* Client application can pass arguments
* Lazy initialization achieved
* Synchronization overhead is minimal and applicable only for first few threads when the variable is null.
*/

public class ASingleton {

    private static volatile ASingleton instance;
    private static Object mutex = new Object();

    private ASingleton() {
    }

    public static ASingleton getInstance() {
        ASingleton result = instance;
        if (result == null) {
            synchronized (mutex) {
                result = instance;
                if (result == null)
                    instance = result = new ASingleton();
            }
        }
        return result;
    }

}
// Thread Safe v3

public class Singleton  {    
    private Singleton() {}

    private static class SingletonHolder {    
        public static final Singleton instance = new Singleton();
    }    

    public static Singleton getInstance() {    
        return SingletonHolder.instance;    
    }    
}

results matching ""

    No results matching ""