Skip to content

Commit

Permalink
Optimize CachedSupplier a little (#119563)
Browse files Browse the repository at this point in the history
This thing shows up a lot in profiling many-shards searches and fields
caps. This is mainly due to expensive `initResult` but we can at least
get a little better cache behavior here on some architectures by saving
one volatile read.
  • Loading branch information
original-brownbear authored Jan 9, 2025
1 parent 547a567 commit 9c9670b
Showing 1 changed file with 12 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
public final class CachedSupplier<T> implements Supplier<T> {

private volatile Supplier<T> supplier;
private volatile T result;
// result does not need to be volatile as we only read it after reading that the supplier got nulled out. Since we null out the
// supplier after setting the result, total store order from an observed volatile write is sufficient to make a plain read safe.
private T result;

public static <R> CachedSupplier<R> wrap(Supplier<R> supplier) {
if (supplier instanceof CachedSupplier<R> c) {
Expand All @@ -38,14 +40,18 @@ public T get() {
if (supplier == null) {
return result;
}
initResult();
return result;
return initResult();
}

private synchronized void initResult() {
if (supplier != null) {
result = supplier.get();
private synchronized T initResult() {
var s = supplier;
if (s != null) {
T res = s.get();
result = res;
supplier = null;
return res;
} else {
return result;
}
}

Expand Down

0 comments on commit 9c9670b

Please sign in to comment.