File tree 3 files changed +75
-1
lines changed
singleton/src/main/java/com/iluwatar 3 files changed +75
-1
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,15 @@ public static void main(String[] args) {
21
21
.getInstance ();
22
22
System .out .println ("threadSafeIvoryTower1=" + threadSafeIvoryTower1 );
23
23
System .out .println ("threadSafeIvoryTower2=" + threadSafeIvoryTower2 );
24
-
24
+
25
+ InitializingOnDemandHolderIdiom demandHolderIdiom = InitializingOnDemandHolderIdiom .getInstance ();
26
+ System .out .println (demandHolderIdiom );
27
+ InitializingOnDemandHolderIdiom demandHolderIdiom2 = InitializingOnDemandHolderIdiom .getInstance ();
28
+ System .out .println (demandHolderIdiom2 );
29
+
30
+ ThreadSafeDoubleCheckLocking dcl1 = ThreadSafeDoubleCheckLocking .getInstance ();
31
+ System .out .println (dcl1 );
32
+ ThreadSafeDoubleCheckLocking dcl2 = ThreadSafeDoubleCheckLocking .getInstance ();
33
+ System .out .println (dcl2 );
25
34
}
26
35
}
Original file line number Diff line number Diff line change
1
+ package com .iluwatar ;
2
+
3
+ import java .io .Serializable ;
4
+
5
+ /**
6
+ *
7
+ * @author mortezaadi@gmail.com
8
+ *
9
+ */
10
+ public class InitializingOnDemandHolderIdiom implements Serializable {
11
+
12
+ private static final long serialVersionUID = 1L ;
13
+
14
+ private static class HelperHolder {
15
+ public static final InitializingOnDemandHolderIdiom INSTANCE = new InitializingOnDemandHolderIdiom ();
16
+ }
17
+
18
+ public static InitializingOnDemandHolderIdiom getInstance () {
19
+ return HelperHolder .INSTANCE ;
20
+ }
21
+
22
+ private InitializingOnDemandHolderIdiom () {
23
+ }
24
+
25
+ protected Object readResolve () {
26
+ return getInstance ();
27
+ }
28
+
29
+ }
Original file line number Diff line number Diff line change
1
+ package com .iluwatar ;
2
+
3
+ /**
4
+ * Broken under Java 1.4.
5
+ * @author mortezaadi@gmail.com
6
+ *
7
+ */
8
+ public class ThreadSafeDoubleCheckLocking {
9
+
10
+ private static volatile ThreadSafeDoubleCheckLocking INSTANCE ;
11
+
12
+ /**
13
+ * private constructor to prevent client from instantiating.
14
+ *
15
+ */
16
+ private ThreadSafeDoubleCheckLocking () {
17
+ //to prevent instantiating by Reflection call
18
+ if (INSTANCE != null )
19
+ throw new IllegalStateException ("Already initialized." );
20
+ }
21
+
22
+ public static ThreadSafeDoubleCheckLocking getInstance () {
23
+ //local variable increases performance by 25 percent
24
+ //Joshua Bloch "Effective Java, Second Edition", p. 283-284
25
+ ThreadSafeDoubleCheckLocking result = INSTANCE ;
26
+ if (result == null ) {
27
+ synchronized (ThreadSafeDoubleCheckLocking .class ) {
28
+ result = INSTANCE ;
29
+ if (result == null ) {
30
+ INSTANCE = result = new ThreadSafeDoubleCheckLocking ();
31
+ }
32
+ }
33
+ }
34
+ return result ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments