I have some code like this
public class MySingleton {
private static MySingleton instance = new MySingleton();
private MySingleton(){}
public static MySingleton getInstance() {
return instance;
} }
This is a hungry implementation for singleton pattern in Java and we know that the instance had been created before getInstance be called.
We also know that a static member will be instantiated when class MySingleton be instantiated. Class MySingleton will be instantiated only when getInstance had been called in this code above. So, the instance had been created after getInstance be called.
So which one is right ??
and why ?
The question is not duplicate.
It doesn't talk about when static class initialization happen but some doubts about hungry implementation for singleton pattern.
May be in this case the class as posted in this question will almost certainly not be initialized until getInstance has been called the first time.