How does lazy initialization work in Singleton?

Can anyone explain how lazy initialization is performed in the following singleton code pattern?

public class Singleton 
{ 
  private static Singleton INSTANCE = null; 
  private Singleton() {} 
  public static Singleton getInstance() 
  { 
    if (INSTANCE == null) 
       INSTANCE = new Singleton(); 
    return INSTANCE; 
  } 
}

      

+3


source to share


3 answers


The first time it is called getInstance()

, INSTANCE

is null, and initialized with INSTANCE = new Singleton();

. This has the advantage of not initializing the instance if it is never used.



This code needs to be improved to be thread safe if it can be accessed by multiple threads.

+7


source


Lazy means that the instance is initialized when it is used for the first time.

Here's an example of impatience, initializing it before using it.



public class Singleton 
{ 
  private static Singleton INSTANCE = new Singleton(); 
  private Singleton() {} 
  public static Singleton getInstance() 
  { 
    return INSTANCE; 
  } 
}

      

+1


source


An instance is only created when the class is initialized and the class is only initialized when called getInstance

.

You might want to visit JLS - 12.4.1. When Initialization Occurs :

The class or interface type T will be initialized just before the first occurrence of any of the following:

T is a class and T is instantiated.

     

T is a class and the static method declared by T is called.

     

Assigned to a static field declared by T.

     

A static field declared by T is used, and the field is not a constant variable (ยง4.12.4).

     

T is a top-level class (ยง7.6) and a statement (ยง14.10) is lexically nested in T (ยง8.1.3).

+1


source







All Articles