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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With