Skip to content

Commit dbc1ca7

Browse files
committed
Add DCL and Initializing on demand holder idiom.
1 parent 70fffc5 commit dbc1ca7

File tree

3 files changed

+75
-1
lines changed

3 files changed

+75
-1
lines changed

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ public static void main(String[] args) {
2121
.getInstance();
2222
System.out.println("threadSafeIvoryTower1=" + threadSafeIvoryTower1);
2323
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);
2534
}
2635
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.iluwatar;
2+
3+
import java.io.Serializable;
4+
5+
/**
6+
*
7+
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+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.iluwatar;
2+
3+
/**
4+
* Broken under Java 1.4.
5+
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+
}

0 commit comments

Comments
 (0)