Singleton Pattern (Java)

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

  • The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.

  • Facade objects are often singletons because only one Facade object is required.

  • State objects are often singletons.

  • Singletons are often preferred to global variables because:

    • They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.

    • They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

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;
    }
}
  • This method has a number of advantages:

    1. The static initializer is run when the class is initialized, after class loading but before the class is used by any thread. (thread-safe)

    2. There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.

    3. The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.

  • weekness

    1. Eager initialization creates the instance even before it's being used.

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 。゚(゚´Д`゚)゚。不要哭!失恋是正常的。女神不也是失恋了吗? Do something with someon...
    凡人Phoebe阅读 149评论 0 0
  • 我路过一片花园,在那条狭窄泥泞的小路的尽头。 那是一个阴暗潮湿的桥洞,两根久经风霜洗礼暗黑斑驳的桥墩支撑着桥面,与...
    追太阳的向日葵阅读 253评论 0 0
  • 最近在学习LINUX的网络环境编译,然而在很多时候并不知道自己的IP,DNS等重要数据,这个时候怎么办呢? 通过贴...
    Neoyyy阅读 291评论 0 0
  • 16-01-25 星期一 晴 23天 习惯了把写字留到晚上。仿佛只有夜晚的静谧才能安下心来。有群友说喜欢在清晨书写...
    年念玲阅读 805评论 0 0
  • 日本经营四圣之一、本田汽车创始人本田宗一郎在自传《奔驰的梦想,我的梦想》中说:“ 我始终认为不需要跟自己个性相同的...
    刘旗阅读 342评论 0 0