Java – double locking mode: disconnected?
Why is this pattern broken? Is it good for me? Any ideas?
public static Singleton getInst() { if (instace == null) createInst(); return instace; } private static synchronized createInst() { if (instace == null) { instace = new Singleton(); } }
Solution
It looks good, but this technology has many subtle problems that should usually be avoided For example, consider the following sequence of events:
Thread a notices that this value is not initialized, so it gets locked and starts initializing the value. > The code generated by the compiler is allowed to update the shared variable to point to the object before partial construction a. the initialization has been completed. > Thread B notifies the shared variable that it has been initialized (and so on) and returns its value Thread B did not acquire the lock because it believed that the value had been initialized If B initializes with all a before the object, the B program may crash
You can avoid this by using the "Volatile" keyword to correctly handle your singleton instance