File tree Expand file tree Collapse file tree 2 files changed +32
-2
lines changed
singleton/src/main/java/com/iluwatar Expand file tree Collapse file tree 2 files changed +32
-2
lines changed Original file line number Diff line number Diff line change 11package 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 */
99public 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments