Skip to content

Commit 4639738

Browse files
quaffjhoeller
authored andcommitted
Eliminate synchronized block to avoid thread pinning in SingletonSupplier
1 parent 09b1e5e commit 4639738

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

spring-core/src/main/java/org/springframework/util/function/SingletonSupplier.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2018 the original author or authors.
2+
* Copyright 2002-2023 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
1616

1717
package org.springframework.util.function;
1818

19+
import java.util.concurrent.locks.Lock;
20+
import java.util.concurrent.locks.ReentrantLock;
1921
import java.util.function.Supplier;
2022

2123
import org.springframework.lang.Nullable;
@@ -31,6 +33,7 @@
3133
* supplier for a method that returned {@code null} and caching the result.
3234
*
3335
* @author Juergen Hoeller
36+
* @author Yanming Zhou
3437
* @since 5.1
3538
* @param <T> the type of results supplied by this supplier
3639
*/
@@ -45,6 +48,11 @@ public class SingletonSupplier<T> implements Supplier<T> {
4548
@Nullable
4649
private volatile T singletonInstance;
4750

51+
/**
52+
* Guards access to write operations on the response.
53+
*/
54+
private final Lock writeLock = new ReentrantLock();
55+
4856

4957
/**
5058
* Build a {@code SingletonSupplier} with the given singleton instance
@@ -90,7 +98,8 @@ private SingletonSupplier(T singletonInstance) {
9098
public T get() {
9199
T instance = this.singletonInstance;
92100
if (instance == null) {
93-
synchronized (this) {
101+
this.writeLock.lock();
102+
try {
94103
instance = this.singletonInstance;
95104
if (instance == null) {
96105
if (this.instanceSupplier != null) {
@@ -102,6 +111,9 @@ public T get() {
102111
this.singletonInstance = instance;
103112
}
104113
}
114+
finally {
115+
this.writeLock.unlock();
116+
}
105117
}
106118
return instance;
107119
}

0 commit comments

Comments
 (0)