源码分析:Spring 单例轮子 - SingletonSupplier

1
2
3
4
5
6
7
8
9
public class MyTest {
// 2024-05-10 16:30
public static void main(String[] args) throws Throwable {

SingletonSupplier<MyTest> supplier = SingletonSupplier.of(MyTest::new);
supplier.get();

}
}

SingletonSupplier源码

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
/**
* @since 5.1
*/
public class SingletonSupplier<T> implements Supplier<T> {

@Nullable
private final Supplier<? extends T> instanceSupplier;

@Nullable
private final Supplier<? extends T> defaultSupplier;

@Nullable
private volatile T singletonInstance;

// ...

@Override
@Nullable
public T get() {
T instance = this.singletonInstance;
if (instance == null) {
synchronized (this) {
instance = this.singletonInstance;
if (instance == null) {
if (this.instanceSupplier != null) {
instance = this.instanceSupplier.get();
}
if (instance == null && this.defaultSupplier != null) {
instance = this.defaultSupplier.get();
}
this.singletonInstance = instance;
}
}
}
return instance;
}

public T obtain() {
T instance = get();
Assert.state(instance != null, "No instance from Supplier");
return instance;
}
// ...
}