-
Notifications
You must be signed in to change notification settings - Fork 1
/
LazySingleton.java
60 lines (51 loc) · 1.57 KB
/
LazySingleton.java
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
// Lazy singleton and thread safety, inner static singleton
package creational.singleton;
class LazySingleton
{
private static LazySingleton instance;
private LazySingleton()
{
System.out.println("initializing a lazy singleton");
}
// 1st approach: synchronized for thread-safety - performance is an issue
// public static synchronized LazySingleton getInstance()
// {
// // Checks if it has been created on lazy loading
// if (instance == null)
// {
// instance = new LazySingleton();
// }
// return instance;
// }
// 2nd approach: double-checked locking: check the instance loading twice
// public static LazySingleton getInstance()
// {
// if (instance == null)
// {
// synchronized (LazySingleton.class)
// {
// if (instance == null)
// {
// instance = new LazySingleton();
// }
// }
// }
// return instance;
// }
}
// 3rd approach: inner static class
class InnerStaticSingleton
{
private InnerStaticSingleton(){}
// inner class here
private static class Impl
{
private static final InnerStaticSingleton
INSTANCE = new InnerStaticSingleton(); // inner classes can access private members of outer classes
}
//Expose instance - this approach avoids the problem of synchronization
public InnerStaticSingleton getInstance()
{
return Impl.INSTANCE;
}
}