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
|
||||
* 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 {
|
||||
|
||||
private static ThreadSafeLazyLoadedIvoryTower instance;
|
||||
private static volatile ThreadSafeLazyLoadedIvoryTower instance;
|
||||
|
||||
private ThreadSafeLazyLoadedIvoryTower() {
|
||||
// protect against instantiation via reflection
|
||||
// Protect against instantiation via reflection
|
||||
if (instance == null) {
|
||||
instance = this;
|
||||
} 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() {
|
||||
if (instance == null) {
|
||||
instance = new ThreadSafeLazyLoadedIvoryTower();
|
||||
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
|
||||
if (instance == null) {
|
||||
instance = new ThreadSafeLazyLoadedIvoryTower();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user