Why is private static field = new Singleton not lazy in Java?

I read a lot of articles about Singleton, most of which the authors said that this variant of Singleton in Java:

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

NOT LAZY (hereinafter EAGER).

But I cannot understand why Singleton() constuctor will be called only when the Singleton class is initialized. I know several reasons that can trigger class initialization:

  • Using new with a constructor (but in this case, the constructor is private).
  • Access to the static field or its setting (here private).
  • Using the static method.
  • With reflection: Class.forName("Singleton") .

Thus, our object will be created only using the static getInstance() method getInstance() still LAZY ) and with reflection (but reflection can destroy many Singleton variations, except enum possible).

Maybe I don’t see anything obvious, please explain where I was wrong?

+6
source share
2 answers

This is mainly a question of the degree of laziness. He is lazy in that he will not create a singleton until the class is initialized, but he longs for some situations when you want to use the class without initializing the singlet itself.

For instance:

 public final class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } public static void sayHello() { System.out.println("Hello!"); } } 

Calling Singleton.sayHello() will instantiate a singleton, even if we don't want it ... so it's not as lazy as it could be.

You can get around this with a nested type:

 public final class Singleton { private Singleton() {} public static Singleton getInstance() { return Holder.instance; } public static void sayHello() { System.out.println("Hello!"); } private static class Holder { private static final Singleton instance = new Singleton(); } } 

Now Singleton.Holder will only be initialized using the getInstance method. It is lazy and without thread without locking.

In my experience, usually the static singleton class method is the getInstance method, in which case they are equivalent (unless you use reflection to initialize the type in some way, for example).

+11
source

This is not lazy because the singeton object is created after the class is loaded.
Lazy Singleton will create the object when it is first used.

+5
source

Source: https://habr.com/ru/post/971529/


All Articles