Improve lazy loaded Singleton example

This commit is contained in:
Ilkka Seppälä 2020-06-10 18:10:34 +03:00
parent e68beb40ec
commit 3033e4c9fc

View File

@ -27,15 +27,13 @@ package com.iluwatar.singleton;
* <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization * <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
* mechanism.</p> * mechanism.</p>
* *
* <p>Note: if created by reflection then a singleton will not be created but multiple options
* in the same classloader</p>
*/ */
public final class ThreadSafeLazyLoadedIvoryTower { public final class ThreadSafeLazyLoadedIvoryTower {
private static ThreadSafeLazyLoadedIvoryTower instance; private static volatile ThreadSafeLazyLoadedIvoryTower instance;
private ThreadSafeLazyLoadedIvoryTower() { private ThreadSafeLazyLoadedIvoryTower() {
// protect against instantiation via reflection // Protect against instantiation via reflection
if (instance == null) { if (instance == null) {
instance = this; instance = this;
} else { } else {
@ -44,13 +42,16 @@ public final class ThreadSafeLazyLoadedIvoryTower {
} }
/** /**
* The instance gets created only when it is called for first time. Lazy-loading * The instance doesn't get created until the method is called for the first time
*/ */
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() { public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
if (instance == null) { if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower(); synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
if (instance == null) {
instance = new ThreadSafeLazyLoadedIvoryTower();
}
}
} }
return instance; return instance;
} }
} }