What's the difference between a static and volatile reference from threading point of view? For example I want to have a singleton object and my code is like this:
class Singleton {
Helper helper; /*Shall I make this variable static or volatile*/
Helper getHelper() {
if(helper==null) {
synchronized(this) {
if(helper==null) {
helper=new Helper();
}
}
}
return helper;
}
}
Suppose there are two threads accessing the getHelper()
method. To avoid multiple creation of Helper object and dirty read shall I make the reference static or volatile?
Can anyone please explain taking thread cache into picture?