-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleton.java
More file actions
58 lines (51 loc) · 1.57 KB
/
Copy pathSingleton.java
File metadata and controls
58 lines (51 loc) · 1.57 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
package inverview.singleton;
public class Singleton {
private volatile static Singleton _instance;
private Singleton() {
// preventing Singleton object instantiation from outside
}
/*
* 1st version: creates multiple instance if two thread access * this method
* simultaneously
*/
public static Singleton getInstance() {
if (_instance == null) {
_instance = new Singleton();
}
return _instance;
}
/*
* * 2nd version : this definitely thread-safe and only * creates one instance
* of Singleton on concurrent environment * but unnecessarily expensive due to
* cost of synchronization * at every call.
*/
public static synchronized Singleton getInstanceTS() {
if (_instance == null) {
_instance = new Singleton();
}
return _instance;
}
/*
* * 3rd version : An implementation of double checked locking of Singleton.
* Intention is to minimize cost of synchronization and improve performance, by
* only locking critical section of code, the code which creates instance of
* Singleton class. By the way this is still broken, if we don't make
* _instance volatile, as another thread can see a half initialized instance of Singleton.
*/
public static Singleton getInstanceDC() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
private static class SingletonHolder{
public static Singleton instance= new Singleton();
}
public static Singleton getInstanceByClassLoadAndInitialized() {
return SingletonHolder.instance;
}
}