Why static fields are not initialized in time?

故事扮演 提交于 2019-12-17 03:24:20

问题


The following code prints null once.

class MyClass {
   private static MyClass myClass = new MyClass();
   private static final Object obj = new Object();
   public MyClass() {
      System.out.println(obj);
   }
   public static void main(String[] args) {}
}

Why are the static objects not initialized before the constructor runs?

Update

I'd just copied this example program without attention, I thought we were talking about 2 Object fields, now I saw that the first is a MyClass field.. :/


回答1:


Because statics are initialized in the order they are given in source code.

Check this out:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static MyClass myClass2 = new MyClass();
  public MyClass() {
    System.out.println(myClass);
    System.out.println(myClass2);
  }
}

That will print:

null
null
myClassObject
null

EDIT

Ok let's draw this out to be a bit more clear.

  1. Statics are initialized one by one in the order as declared in the source code.
  2. Since the first static is initialized before the rest, during its initialization the rest of the static fields are null or default values.
  3. During the initiation of the second static the first static is correct but the rest are still null or default.

Is that clear?

EDIT 2

As Varman pointed out the reference to itself will be null while it is being initialized. Which makes sense if you think about it.




回答2:


Let's try a different way to explain this...

This is the sequence the JVM goes through when you first reference the class MyClass.

  1. Load the byte-code into memory.
  2. Memory for the static storage is cleared (binary zero).
  3. Initialize the class:
    1. Execute each static initializer in the order that it appears, this includes static variables and static { ... } blocks.
    2. JVM then initializes your myClass static variable to a new instance of MyClass.
    3. When this happens, the JVM notices that MyClass is already loaded (byte-code) and in the process of being initialized, so it skips initialization.
    4. Allocate memory on heap for object.
    5. Execute constructor.
    6. Print out value of obj which is still null (since it is not part of the heap and constructor initialized variables).
    7. When constructor finishes, execute next static initializer which sets obj to a new instance of Object.
  4. Class initialization done. From this point, all constructor calls will behave as you presume/expect - that is obj would not be null but a reference to an Object instance.

Remember that Java specifies that a final variable is assigned a value once. It is not that it is guaranteed to be assigned a value when the code references it unless you ensure that the code references it after it is assigned.

This is not a bug. This is the defined way to handle usage of the class during its own initialization. If this were not so, then the JVM would go into an infinite loop. See step #3.3 (if the JVM does not skip initialization for a class that is in the process of initialization it would just keep initializing it - infinite loop).

Note as well, this all happens on the same thread that first references the class. Second, the JVM guarantees that initialization will complete before any other thread is allowed to use this class.




回答3:


That's because Java executes the static section in order it is declared. In your case, the sequence is

  1. new MyClass
  2. new Object

When #1 is executed, obj is still not initialized, so it prints null. Try the following and you will see the difference:

class MyClass {
  private static final Object obj = new Object();
  private static MyClass myClass = new MyClass();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

Generally speaking, it is better to avoid such a construct all together. If you are trying to create a singleton, that's how that code fragment should look like:

class MyClass {

  private static final MyClass myClass = new MyClass();

  private Object obj = new Object();

  private MyClass() {
    System.out.println(obj); // will print null once
  }
}



回答4:


that is because static fields initialized in same order they defined.




回答5:


@Pyrolistical

since the initial of first static field myclass is not fully constructed ...the result i get is

null null testInitialize.MyObject@70f9f9d8 null



来源:https://stackoverflow.com/questions/2547713/why-static-fields-are-not-initialized-in-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!