javasingletondcl

Why a static singleton is a simple and elegant solution to avoid 'DCL'?


When need a singleton, is a static field a elegant solution?

class HelperSingleton {
  static Helper singleton = new Helper();

  public static Helper getInstance() {
       return singleton;
     }
  }

When two threads access to getInstance at the same time, is there a chance the field singleton is not initialized completely? Or see the default values for fields of the helper object, rather than the values set in the constructor? Static singleton is also lazy initialization?

I mean, static Helper singleton = new Helper(); is this assigment atomic? And won't return default values ?


Solution

  • 1) When a thread accesses static getInstance the first time class loader has to load the HelperSingleton class and it will lock other thread before class is loaded. So there is an implicit synchronization present. J.Bloch "Effective Java" Item 71 modern VM will synchronize field access only to initialize the class. Once the class is initialized, the VM will patch the code so that subsequent access to the field does not involve any testing or synchronization.

    2) Your singleon is lazy, because there is only one access point - getInstance. Not only instance is created on demand but the whole class is loaded on demand. A class will not be initialized until it is used [JLS, 12.4.1].