Skip to content

Commit 3033e4c

Browse files
committed
Improve lazy loaded Singleton example
1 parent e68beb4 commit 3033e4c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,13 @@
2727
* <p>Thread-safe Singleton class. The instance is lazily initialized and thus needs synchronization
2828
* mechanism.</p>
2929
*
30-
* <p>Note: if created by reflection then a singleton will not be created but multiple options
31-
* in the same classloader</p>
3230
*/
3331
public final class ThreadSafeLazyLoadedIvoryTower {
3432

35-
private static ThreadSafeLazyLoadedIvoryTower instance;
33+
private static volatile ThreadSafeLazyLoadedIvoryTower instance;
3634

3735
private ThreadSafeLazyLoadedIvoryTower() {
38-
// protect against instantiation via reflection
36+
// Protect against instantiation via reflection
3937
if (instance == null) {
4038
instance = this;
4139
} else {
@@ -44,13 +42,16 @@ private ThreadSafeLazyLoadedIvoryTower() {
4442
}
4543

4644
/**
47-
* The instance gets created only when it is called for first time. Lazy-loading
45+
* The instance doesn't get created until the method is called for the first time
4846
*/
4947
public static synchronized ThreadSafeLazyLoadedIvoryTower getInstance() {
5048
if (instance == null) {
51-
instance = new ThreadSafeLazyLoadedIvoryTower();
49+
synchronized (ThreadSafeLazyLoadedIvoryTower.class) {
50+
if (instance == null) {
51+
instance = new ThreadSafeLazyLoadedIvoryTower();
52+
}
53+
}
5254
}
53-
5455
return instance;
5556
}
5657
}

0 commit comments

Comments
 (0)