Singleton Pattern (Java)

2016-11-18  本文已影响0人  iamkai

This article is part of Reference 1 and Reference 2. I just organize them in my own way.

GOF definition

Ensure a class only has one instance, and provide a global point of access to it.

Common use

Java implementation

Eager initialization

If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization.

public class Singleton{
    private static final Singleton INSTANCE = new Singleton();

    // private constructor avoid client to use
    private Singleton(){}
    
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

Static block initialization

Some authors refer to a similar solution allowing some pre-processing (e.g. for error-checking).

public class Singleton {
    private static final Singleton instance;

    static {
        try {
            instance = new Singleton();
        } catch (Exception e) {
            throw new RuntimeException("error", e);
        }
    }

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {}
}

Lazy initialization

no thread-safe

public class Singleton{
    private static Singleton instance = null;
    private SingletonDemo() { }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }
}

simple thread-safe

public class Singleton{
    private static Singleton instance = null;
    private Singleton() { }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }
}

Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances. To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

double-checked locking

public class Singleton{
    private static volatile Singleton instance;
    private Singleton() { }

    public static Singleton getInstance() {
        if (instance == null ) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}

Initialization-on-demand holder idiom

Prior to Java 5, java memory model had a lot of issues and double-checked locking approach used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously. So Bill Pugh came up with a different approach to create the Singleton class using a inner static helper class

public class Singleton {
       
        private Singleton() { }
        
        private static class SingletonHelpder {
                private static final Singleton INSTANCE = new Singleton();
        }

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

Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.

This approach has both advantages, thread-safe and lazy load.

Using Reflection to destroy Singleton Pattern

Reflection can be used to destroy all the above singleton implementation approaches. Let’s see this with an example class.

import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {
  public static void main(String[] args) {
      Singleton instanceOne = Singleton.getInstance();
      Singleton instanceTwo = null;

      try {
        Constructor[] constructors = Singleton.class.getDeclaredConstructors();

          for (Constructor constructor : constructors) {
              // Below code will destroy the singleton pattern
              constructor.setAccessible(true);
              instanceTwo = (Singleton)constructor.newInstance();
              break;
          }
      } catch (Exception e) {

          e.printStackTrace();
      }
      System.out.println(instanceOne.hashCode());
      System.out.println(instanceTwo.hashCode());
  }

}

When you run the above test class, you will notice that hashCode of both the instances are not same that destroys the singleton pattern. Reflection is very powerful and used in a lot of frameworks like Spring and Hibernate.

The enum way

To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.

public enum Singleton {
    INSTANCE;
    
    public static void doSomething(){
        //do something
    }
}

Reference

  1. Java Singleton Design Pattern Best Practices with Examples - Pankaj
  2. Singleton pattern - wiki
  3. Java设计模式(一)----单例模式 - 汤高
  4. What is an efficient way to implement a singleton pattern in Java? - stackoverflow
上一篇 下一篇

猜你喜欢

热点阅读