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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package io.github.binglau;

import java.util.function.Supplier;

/**
* 文件描述: 懒加载大对象 Heavy
* 利用类加载机制达到 LazyLoad 为单例
*/

public final class LazyLoad {
private LazyLoad() {
}

private static class Holder {
private static final LazyLoad INSTANCE = new LazyLoad();
}

public static final LazyLoad getInstance() {
return Holder.INSTANCE;
}

private Supplier<Heavy> heavy = this::createAndCacheHeavy;
private Normal normal = new Normal();

public Heavy getHeavy() {
return heavy.get();
}

public Normal getNormal() {
return normal;
}

private synchronized Heavy createAndCacheHeavy() {
class HeavyFactory implements Supplier<Heavy> {
private final Heavy heavyInstance = new Heavy();
@Override
public Heavy get() {
return heavyInstance;
}
}

if (!HeavyFactory.class.isInstance(heavy)) {
heavy = new HeavyFactory();
}

return heavy.get();
}

public static void main(String[] args) throws InterruptedException {
LazyLoad.getInstance().getNormal();
LazyLoad.getInstance().getHeavy();
}

}

class Heavy {
public Heavy() {
System.out.println("Creating Heavy ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("... Heavy created");
}
}

class Normal {
public Normal() {
System.out.println("Creating Normal ...");
System.out.println("... Normal created");
}
}