Skip to content

Commit 5687976

Browse files
committed
Thread-safe Singleton class
New Singleton class name has renamed to ThreadSafeLazyLoadedIvoryTower and called it from App.java
1 parent cffe592 commit 5687976

File tree

3 files changed

+32
-20
lines changed

3 files changed

+32
-20
lines changed

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package com.iluwatar;
22

33
/**
4-
*
4+
*
55
* Singleton pattern ensures that the class (IvoryTower) can have only one
66
* existing instance and provides global access to that instance.
7-
*
7+
*
88
*/
99
public class App {
1010

@@ -15,5 +15,12 @@ public static void main(String[] args) {
1515
System.out.println("ivoryTower1=" + ivoryTower1);
1616
System.out.println("ivoryTower2=" + ivoryTower2);
1717

18+
ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower1 = ThreadSafeLazyLoadedIvoryTower
19+
.getInstance();
20+
ThreadSafeLazyLoadedIvoryTower threadSafeIvoryTower2 = ThreadSafeLazyLoadedIvoryTower
21+
.getInstance();
22+
System.out.println("threadSafeIvoryTower1=" + threadSafeIvoryTower1);
23+
System.out.println("threadSafeIvoryTower2=" + threadSafeIvoryTower2);
24+
1825
}
1926
}

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

Lines changed: 0 additions & 18 deletions
This file was deleted.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.iluwatar;
2+
3+
/**
4+
*
5+
* Thread-safe Singleton class.
6+
*
7+
*/
8+
public class ThreadSafeLazyLoadedIvoryTower {
9+
10+
private static ThreadSafeLazyLoadedIvoryTower instance = null;
11+
12+
public synchronized static ThreadSafeLazyLoadedIvoryTower getInstance() {
13+
/*
14+
* The instance gets created only when it is called for first time.
15+
* Lazy-loading
16+
*/
17+
if (instance == null) {
18+
instance = new ThreadSafeLazyLoadedIvoryTower();
19+
}
20+
21+
return instance;
22+
}
23+
}

0 commit comments

Comments
 (0)