Java double checked locking

Double check locking is broken. Since initialized is a primitive, it may not require it to be volatile to work, however nothing prevents initialized being seen as true to the non-syncronized code before instance is initialized. EDIT: To clarify the above answer, the original question asked about using a boolean to control the double check … Read more

What is the point of making the singleton instance volatile while using double lock? [duplicate]

The volatile prevents memory writes from being re-ordered, making it impossible for other threads to read uninitialized fields of your singleton through the singleton’s pointer. Consider this situation: thread A discovers that uniqueInstance == null, locks, confirms that it’s still null, and calls singleton’s constructor. The constructor makes a write into member XYZ inside Singleton, … Read more

why using volatile with synchronized block?

Synchronization by itself would be enough in this case if the first check was within synchronized block (but it’s not and one thread might not see changes performed by another if the variable were not volatile). Volatile alone would not be enough because you need to perform more than one operation atomically. But beware! What … Read more

Why is volatile used in double checked locking

A good resource for understanding why volatile is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well. The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. … Read more