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();
}
}
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:
not initialized, so it obtains the
lock and begins to initialize the
value.
to update the shared variable to
point to a partially constructed
object before A has finished
performing the initialization.
variable has been initialized (or so
it appears), and returns its value.
Because thread B believes the value
is already initialized, it does not
acquire the lock. If B uses the
object before all of the
initialization done by A is seen by
B the program will likely crash.
You could avoid this by using the “volatile” keyword to handle your singleton instances correctly