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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,098评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,213评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,960评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,519评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,512评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,533评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,914评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,574评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,804评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,563评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,644评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,350评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,933评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,908评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,146评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,847评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,361评论 2 342

推荐阅读更多精彩内容

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