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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值