'Initialization and volatile in Java singleton

I was thinking about why we should use volatile keyword on instance field.

class Test {

  private static /* volatile */ Test instance;

  public static Test getInstance() {

    if (instance == null) {

      synchronized (Test.class) {

        if (instance == null) {
          instance = new Test();
        }

      }

    }
    return instance;
  }


}

Then I looked at bytecode. I suppose that we use volatile because instructions of constructor invocation and field assignment could be rearranged too? Am I getting it right?

        10: monitorenter
        11: getstatic     #7                  // Field instance:LTest;
        14: ifnonnull     27
        17: new           #8                  // class Test
        20: dup
        21: invokespecial #13                 // Method "<init>":()V
        24: putstatic     #7                  // Field instance:LTest;
        27: aload_0
        28: monitorexit


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source