Skip to content

Commit

Permalink
Eliminate synchronized block to avoid thread pinning in SingletonSupp…
Browse files Browse the repository at this point in the history
…lier
  • Loading branch information
quaff authored and jhoeller committed Sep 14, 2023
1 parent 09b1e5e commit 4639738
Showing 1 changed file with 14 additions and 2 deletions.
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

0 comments on commit 4639738

Please sign in to comment.