Posted in Multithreading

Synchronized Singleton

Double-checked locking has been proven to be incorrect and flawed (as least in Java). Do a search or look at Wikipedia’s entry for the exact reason.

First and foremost is program correctness. If your code is not thread-safe (in a multi-threaded environment) then it’s broken. Correctness comes first before performance optimization.

To be correct you’ll have to synchronize the whole getInstance method

public static synchronized Singleton getInstance() {
   if (instance==null) ...

or statically initialize it

private static final Singleton INSTANCE = new Singleton();