Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

singleton public static final

Tags:

java

singleton

I've been wondering about singletons in Java. By convention, a singleton is set up something like this:

private static MyClass instance = null;
public static MyClass getInstance(){
    if (instance == null){
        instance = new MyClass();
    }
    return instance;
}
private MyClass(){}

Recently I've switched to using the following:

public static final MyClass instance = new MyClass();
private MyClass(){}

This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?

like image 335
Daniël van den Berg Avatar asked Mar 23 '26 04:03

Daniël van den Berg


1 Answers

The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized

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. [...]

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization.

The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.

Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).

Note: the first version is not thread safe in the pasted snippet

like image 119
Raffaele Avatar answered Mar 25 '26 18:03

Raffaele