I am trying to understand the following code snippet that apparently is a lazy-loading example of the singleton attribute in the LazyHolder class.
class Singleton {
// My private inner class containing my future lazy loading attribute
private static class LazyHolder {
private static Singleton singleton = new Singleton();
}
public static Singleton getSingleton() {
return LazyHolder.singleton;
}
}
class Main {
public static main(String[] args) {
Singleton s = Singleton.getSingleton();
}
}
According to some online courses I have been following, the private static singleton instance will be created at the line:
Singleton s = Singleton.getSingleton()
But since the singleton attribute is static, I thought it's created during the LazyHolder class definition. So my question is:
When is the LazyHolder class really created?
- is it created when the
Singletonclass is created, becauseLazyHolderis an attribute ofSingletonclass, or - is it created when we enter in the
getSingleton()method ofSingletonclass?
I would really appreciate an explanation of what's happening during the runtime execution.