Why is the pattern considered broken? It looks fine to me? Any ideas?
public static Singleton getInst() {
if (instace == null) createInst();
return instace;
}
private static synchronized createInst() {
if (instace == null) {
instace = new Singleton();
}
}
Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment. Unfortunately, it will not work reliably in a platform independent way when implemented in Java, without additional synchronization.
Since only the first access requires locking, double-checked locking is used to avoid locking overhead of subsequent accesses. However, on many languages and hardware, the design can be unsafe.
The only way to do double-checked locking correctly in Java is to use "volatile" declarations on the variable in question. While that solution is correct, note that "volatile" means cache lines get flushed at every access.
Ans. There is no mapping of single ton with number of processor of the system. So double check locking will not fail depending on number of processor.
It looks okay at first glance, but this technique has many subtle problems and should usually be avoided. For example, consider the following sequence of events:
You could avoid this by using the "volatile" keyword to handle your singleton instances correctly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With