Linda
Linda

Reputation: 217

How does lazy initialization happen in Singleton?

Can anyone explain how does lazy initialization happen in the following singleton pattern code?

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

Upvotes: 3

Views: 1024

Answers (3)

outdev
outdev

Reputation: 5492

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

Here is an example of eager, its initialized before its used.

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

Upvotes: 1

Maroun
Maroun

Reputation: 95958

The instance is created only when the class is initialized, and the class is initialized only when you call getInstance.

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

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.

T is a class and a static method declared by T is invoked.

A static field declared by T is assigned.

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 an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

Upvotes: 1

Eran
Eran

Reputation: 393801

The first time getInstance() is called, INSTANCE is null, and it is initialized with INSTANCE = new Singleton();. This has the advantage of not initializing the instance if it is never used.

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

Upvotes: 7

Related Questions