Java Language Singleton without use of Enum (eager initialization)


Example

public class Singleton {    

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

It can be argued that this example is effectively lazy initialization. Section 12.4.1 of the Java Language Specification states:

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
  • T is a top level class, and an assert statement lexically nested within T is executed.

Therefore, as long as there are no other static fields or static methods in the class, the Singleton instance will not be initialized until the method getInstance() is invoked the first time.