Improve lazy loaded Singleton example
This commit is contained in:
parent
e68beb40ec
commit
3033e4c9fc
@ -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) {
|
||||||
|
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
|
||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
instance = new ThreadSafeLazyLoadedIvoryTower();
|
instance = new ThreadSafeLazyLoadedIvoryTower();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user