-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleton.java
More file actions
71 lines (52 loc) · 1.51 KB
/
Copy pathSingleton.java
File metadata and controls
71 lines (52 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package singleton;
import java.util.ArrayList;
class SingletonEager {
private static SingletonEager singletonObject = new SingletonEager();
private SingletonEager() { }
public static SingletonEager getInstance() {
return singletonObject;
}
}
// Lazy Initialization
class SingletonLazy {
private static SingletonLazy singleton = null;
private SingletonLazy() { }
public static SingletonLazy getInstance() {
if(singleton == null) {
singleton = new SingletonLazy();
}
return singleton;
}
}
// Lazy Initialization with Synchronization
class SingletonSync {
private static SingletonSync singleton = null;
private SingletonSync() { }
// 1000 threads, T1
public synchronized static SingletonSync getInstance() {
// for loop
if(singleton == null) {
singleton = new SingletonSync();
}
return singleton;
}
}
// Lazy Initialization with Synchronization Double Locking
public class Singleton {
private static Singleton singleton = null;
private Singleton() { }
// 1000 threads, T1
public static Singleton getInstance() {
// for loop, T2
if(singleton == null) {
// T1 => singleton1 = new Singleton()
// T2 => singleton2 = new Singleton()
synchronized (Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}