the new operator is allowed to return the value until the class constructor completes. Thus, the variable may not read null, but contains an uninitialized instance of the class. This is due to byte reordering.
Some clarifications: From the point of view of a single JVM thread, it is allowed to reorder commands. When creating an instance, traditionally you think it looks like this:
- allocate memory
- start initialization (constructor)
- assign a link to var
Although in fact the JVM can do something like:
- allocate memory
- assign a link to var
- start initialization (Constructor)
This has performance advantages, as addresses do not need to be searched again. From the point of view of a single thread, this does not change the order of logic. The program works great. But this creates a problem in multi-threaded code. This means that the link can be published before the constructor starts. To do this, you must follow the "happens sooner" rule to make sure that the instance is fully initialized. Declaring volatile dos variables enforces such rules — up to rules.
More on reordering: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#reordering
source share