Skip to content

Eliminate synchronized block to avoid thread pinning in SingletonSupplier #31227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,8 @@

package org.springframework.util.function;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

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

/**
* Guards access to write operations on the response.
*/
private final Lock writeLock = new ReentrantLock();


/**
* Build a {@code SingletonSupplier} with the given singleton instance
Expand Down Expand Up @@ -90,7 +98,8 @@ private SingletonSupplier(T singletonInstance) {
public T get() {
T instance = this.singletonInstance;
if (instance == null) {
synchronized (this) {
this.writeLock.lock();
try {
instance = this.singletonInstance;
if (instance == null) {
if (this.instanceSupplier != null) {
Expand All @@ -102,6 +111,9 @@ public T get() {
this.singletonInstance = instance;
}
}
finally {
this.writeLock.unlock();
}
}
return instance;
}
Expand Down