1

I have some code like this

public class MySingleton {  

private static MySingleton instance = new MySingleton();  

private MySingleton(){}  

public static MySingleton getInstance() {  
    return instance;  
}  }  
  1. This is a hungry implementation for singleton pattern in Java and we know that the instance had been created before getInstance be called.

  2. 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.

huster
  • 67
  • 5
  • 1
    Not clear to me if this question is a duplicate of "When does static class initialization happen?" This question is about the correctness of the proposed Singleton implementation. – Duloren Jul 05 '17 at 16:49
  • The class member isn't instantiated after the class is instantiated in this case, it's instantiated when the class is initialized, which is, again in this case, upon the first call to `getInstance`. However, do bear in mind that this is an unnecessarily complex implementation of a singleton. A simpler one is `public enum Singleton { INSTANCE; }`. – Lew Bloch Jul 05 '17 at 17:55

1 Answers1

0

2nd statement is false, static members are initialized when the class they are in is loaded, not when the first instance of that class is created.

It is easy to show because you do not need an instance of a class to access its static members i.E. MyClass.intVar = 5 works fine. You do not need to instantiate MyClass first.

CrowsNet
  • 93
  • 5
  • 1
    Static members of a class are _not_ initialized when the class is loaded! They're initialized when the class is initialized. The class as posted in this question will almost certainly not be initialized until `getInstance` has been called the first time. At that time the instance will be initialized for the static reference, and not until then, or at least not until some other qualifying event occurs, but this code doesn't admit of other qualifying events. – Lew Bloch Jul 05 '17 at 17:52
  • I got it, thank you ! – huster Jul 06 '17 at 01:45