I have read that double checking mechanism for singleton is a failure, because of some memory model followed by JVM which makes the reference read not null even if the constructor has not got executed completely.
I tried testing the same by making an time taking operation inside the constructor in the below code but even then it seems to be working fine.
public class Singleton {
private static Singleton singleton;
private Integer i = 0;
private Singleton() {
for(long j = 0; j<99999999; j++){
double k = Math.random();
k= k+1;
}
i = 10;
}
private static Singleton getSinglton() {
if(singleton == null){
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
public static void main(String[] args) {
Runnable runnable1 = new Runnable() {
@Override
public void run() {
Singleton singleton = Singleton.getSinglton();
System.out.println(singleton.getI());
}
};
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable1);
Thread t3 = new Thread(runnable1);
Thread t4 = new Thread(runnable1);
Thread t5 = new Thread(runnable1);
Thread t6 = new Thread(runnable1);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
public void setI(Integer i) {
this.i = i;
}
public Integer getI() {
return i;
}
}
The result I get is 10 10 10 10 10 10
I was expecting few threads to read value 0 , instead of 10, but each time the value is correctly read as 10 , so it the issue solved in Java SE-1.6 as I am using the same ?