Synchronized singleton with double-checked locking mechanism
The previous implementation is thread-safe but it introduces an unnecessary delay: the block that checks whether the instance has already been created is synchronized. This means that the block can be executed by only one thread at a time, but locking makes sense only when the instance has not been created. When the singleton instance has already been created, each thread can get the current instance in an unsynchronized manner.
Adding an additional condition before the synchronized block will move the thread-safe locking only when the singleton has not been instantiated yet:
if (instance == null) { synchronized (SingletonSync2.class) { if (instance == null) instance = new SingletonSync2(); } }
Note that instance == null is checked twice. This is necessary, because we have to make sure a check is done in the synchronized block too.