June 2018
Intermediate to advanced
280 pages
7h 46m
English
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(); ...Read now
Unlock full access