Mainak Mainak - 29 days ago 20
Java Question

Singleton with Enum called by threads

Hi can any one help me understand the output of the below snippet?

Enum -

public enum SingletonEnum {
INSTANCE;
int num;

public void demo(){
System.out.println(num);
}
}


Main Class -

public static void main(String[] args) {
Thread t1 = new Thread(new Runnable(){
public void run(){
SingletonEnum samp = SingletonEnum.INSTANCE;
samp.num= 5;
samp.demo();
}
});

Thread t2 = new Thread(new Runnable(){
public void run(){
SingletonEnum temp = SingletonEnum.INSTANCE;
temp.num= 8;
temp.demo();
}
});
t1.start();
t2.start();
}


The o/p is 8 and 8 .However if i add a private constructor in the enum the o/p is 5 and 8. What is the logic behind the o/p being 8 and 8.

Answer

You code is not synchronized. This is simply unspecified behavior, you can observe anything in such case.