1
1
/*
2
- * Copyright 2002-2018 the original author or authors.
2
+ * Copyright 2002-2023 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
16
16
17
17
package org .springframework .util .function ;
18
18
19
+ import java .util .concurrent .locks .Lock ;
20
+ import java .util .concurrent .locks .ReentrantLock ;
19
21
import java .util .function .Supplier ;
20
22
21
23
import org .springframework .lang .Nullable ;
31
33
* supplier for a method that returned {@code null} and caching the result.
32
34
*
33
35
* @author Juergen Hoeller
36
+ * @author Yanming Zhou
34
37
* @since 5.1
35
38
* @param <T> the type of results supplied by this supplier
36
39
*/
@@ -45,6 +48,11 @@ public class SingletonSupplier<T> implements Supplier<T> {
45
48
@ Nullable
46
49
private volatile T singletonInstance ;
47
50
51
+ /**
52
+ * Guards access to write operations on the response.
53
+ */
54
+ private final Lock writeLock = new ReentrantLock ();
55
+
48
56
49
57
/**
50
58
* Build a {@code SingletonSupplier} with the given singleton instance
@@ -90,7 +98,8 @@ private SingletonSupplier(T singletonInstance) {
90
98
public T get () {
91
99
T instance = this .singletonInstance ;
92
100
if (instance == null ) {
93
- synchronized (this ) {
101
+ this .writeLock .lock ();
102
+ try {
94
103
instance = this .singletonInstance ;
95
104
if (instance == null ) {
96
105
if (this .instanceSupplier != null ) {
@@ -102,6 +111,9 @@ public T get() {
102
111
this .singletonInstance = instance ;
103
112
}
104
113
}
114
+ finally {
115
+ this .writeLock .unlock ();
116
+ }
105
117
}
106
118
return instance ;
107
119
}
0 commit comments