Kar started this conversation 3 months ago.
Lazy Initialization Race Condition: Double checked Locking Without volatile
I implemented a singleton pattern using double checked locking without declaring the instance variable as volatile. In multithreaded environments, occasionally two threads create separate instances or one receives an incompletely initialized object. Why is this happening?
Digiaru
Posted 3 months ago
Without volatile, the JVM may reorder writes so that another thread sees a non-null reference before the object is fully constructed—leading to either duplicate instances or corrupted state. This is due to Java memory model visibility issues pre Java 5 ([turn0search5][turn0search12]). Fix: • Declare the helper instance as private volatile Helper helper; • Use proper double-checked locking with volatile • Alternatively, use the initialization on demand holder idiom: java Copy code class Foo { private static class Holder { static final Helper HELPER = new Helper(); } public static Helper getHelper() { return Holder.HELPER; } } This ensures thread safety without synchronization overhead.