educative.io

Educative

Could someone elaborate this?

The above solution marks the singleton instance volatile however the JVM volatile implementation for Java versions 1.4 will not work correctly for double checked locking and you’ll need to use another way to create your singletons.

What are another ways?

@Nilesh_Jha From what I found from my digging around this topic, it seems the problem lied with how the volatile was implemented in previous Java specifications.

Compilers can reorder the instructions in the name of optimization if in case it sees fit that the operations are independent. Such reorderings are subtle and don’t come to light
when we have a single threaded program. In Multi threaded cases these reorderings can create differences.

Older Java memory models ensured that the compiler will not reorder the volatile variables. But it was still free to do the reorders of nonvolatile variables around the volatile variables
consider the case :

public PotentialBug{
int a=100 //initial value;
volatile int b=50;

public doThisStuffFirst(){
    a=90;
    b=20;
}

private static doStuff(){
    if(b==20){
        //doStuff with a
        //not guaranteed that a=90; in <jdk5
        //guaranteed that a=90; in jdk >=5
    }
}

}

previous implementations would not have guaranteed the reordering of the writes of a & b in doThisStuffFirst since a is nonvolatile and can be reordered. There could have been a case
where a Thread who is using doStuff would read a’s value as 100 instead of 90 which it should be assuming that b’s value has definitely changed to 20.

Under new implementations from jdk5, the volatile’s reordering now is more robust to include the reorderings of the non volatile fields surrounding it as well. Now the same code
will guarantee that a’s value has been changed to 90 since the write to b would have released the the write to a in memory first in the doStuffFirst method.