3

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; 
  } 
}
Eran
  • 387,369
  • 54
  • 702
  • 768
Linda
  • 217
  • 2
  • 7
  • 1
    From [Wikipedia about Lazy Initialization](http://en.wikipedia.org/wiki/Lazy_initialization): "[...] lazy initialization is the tactic of _delaying_ the creation of an object [...]" – Seelenvirtuose Dec 08 '14 at 09:47
  • 1
    For a good way to do lazy initialization, see [this question about how Scala does it](https://stackoverflow.com/questions/17642275/how-are-lazy-val-class-variables-implemented-in-scala-2-10). – Chris Martin Dec 08 '14 at 09:49
  • 1
    "Without thread safety" is one answer. See [this answer](http://stackoverflow.com/a/16106598/256196) for one of the standard idioms. – Bohemian Dec 08 '14 at 09:52

3 Answers3

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    `public enum Singleton { INSTANCE; public void method() { ... } }` This is the best way how to make thread safe singleton (Thx Joshua Bloch) – Milkmaid Dec 08 '14 at 09:53
1

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; 
  } 
}
outdev
  • 5,249
  • 3
  • 21
  • 38
1

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241