How reading (outside critical resource block) and writing (inside critical resource block) does not have atomicity issues.
I have read and discussed with various people but most people don't answer if both operations are atomic and how atomicity is actually achieved for above problem.
class ABC {
private static volatile ABC abcInstance;
static ABC getInstance(){
if(abcInstance == null){
synchronized(ABC.class){
if(abcInstance == null){
abcInstance = new ABC();
return abcInstance;
}
}
}
return abcInstance;
}
}
Are if(abcInstance == null) outside synchronisation block
and abcInstance = new ABC();
atomic, if not then this way of creating singletons is wrong.
In C++, abcInstance = new ABC();
consists of three instructions broadly speaking:
- Create ABC object.
- Allocate memory for ABC.
- Assign it to abcInstance.
And for optimisations compiler can reorder these three instructions in any way. Suppose it follows 2->3->1 and after instruction 3 interrupt happens and next thread calling getInstance() will read that abcInstance has some value then it will point to something which does not have ABC object.
Please correct me if am wrong for both C++ and Java.