
Digiaru started this conversation 4 days ago.
Double Checked Locking Singleton Bug Without volatile
I implemented a singleton using double-checked locking but occasionally end up with multiple instances or a partially constructed object. Why does this happen?
Kar
Posted 4 days ago
Without marking the shared instance as volatile, JVM optimizations may reorder writes—causing another thread to see a partially initialized object or create a second instance ([turn0search26]turn0search12]). Fixes: • Add volatile: java Copy code private static volatile MySingleton instance; • Or use the Initialization-on-demand holder idiom: java Copy code private static class Holder { static final MySingleton INSTANCE = new MySingleton(); } public static MySingleton getInstance() { return Holder.INSTANCE; } This is thread-safe, lazy, and avoids synchronization overhead.