Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager instantiation of Singleton

Tags:

java

singleton

I have a Singleton

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

     private Singleton()
     {
         System.out.println("Instance created.");
     }

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

I can run this code, but the instance is not being created unless getInstance() gets called. This is weird, as my println() in the constructor should execute since I am using eager instantiation.

Can someone explain?

like image 946
user3648439 Avatar asked Dec 25 '22 09:12

user3648439


2 Answers

instance will not get created until the class will get loaded for the first time, if you want eager initialization without invoking getInstance() method you can call

Class.forName(Singleton.class.getName());

on initialization

you have instance as static field, and static field gets initialized on class load event, so if you want eager initialization you just load class eagerly

like image 196
jmj Avatar answered Dec 28 '22 06:12

jmj


Once the class is accessed somewhere in the code, all the static variables associated with it are loaded and assigned their values.

If the first point in your program where the class is used is the point where you call getInstance(), then the class will be loaded there, the static variable will be initialized, and the constructor will be run.

like image 20
APerson Avatar answered Dec 28 '22 07:12

APerson