• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ben-manes / caffeine / #5847

28 Nov 2026 02:39AM UTC coverage: 99.989%. Remained the same
#5847

push

github

ben-manes
restore coverage lost to recent fixes

4924 of 4934 branches covered (99.8%)

6 of 6 new or added lines in 2 files covered. (100.0%)

1 existing line in 1 file now uncovered.

9372 of 9373 relevant lines covered (99.99%)

1.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.25
/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalAsyncLoadingCache.java
1
/*
2
 * Copyright 2015 Ben Manes. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package com.github.benmanes.caffeine.cache;
17

18
import static com.github.benmanes.caffeine.cache.Caffeine.calculateHashMapCapacity;
19
import static com.github.benmanes.caffeine.cache.Caffeine.hasMethodOverride;
20
import static com.github.benmanes.caffeine.cache.Caffeine.toUnchecked;
21
import static com.github.benmanes.caffeine.cache.LocalAsyncCache.composeResult;
22
import static java.util.Objects.requireNonNull;
23

24
import java.lang.System.Logger;
25
import java.lang.System.Logger.Level;
26
import java.util.LinkedHashMap;
27
import java.util.Map;
28
import java.util.Set;
29
import java.util.concurrent.CancellationException;
30
import java.util.concurrent.CompletableFuture;
31
import java.util.concurrent.Executor;
32
import java.util.concurrent.TimeoutException;
33
import java.util.function.BiFunction;
34

35
import org.jspecify.annotations.Nullable;
36

37
import com.google.errorprone.annotations.Var;
38

39
/**
40
 * This class provides a skeletal implementation of the {@link AsyncLoadingCache} interface to
41
 * minimize the effort required to implement a {@link LocalCache}.
42
 *
43
 * @author ben.manes@gmail.com (Ben Manes)
44
 */
45
abstract class LocalAsyncLoadingCache<K, V>
46
    implements LocalAsyncCache<K, V>, AsyncLoadingCache<K, V> {
47
  static final Logger logger = System.getLogger(LocalAsyncLoadingCache.class.getName());
1 ✔
48

49
  final @Nullable BiFunction<? super Set<? extends K>, ? super Executor,
50
      ? extends CompletableFuture<? extends Map<? extends K, ? extends V>>> bulkMappingFunction;
51
  final BiFunction<? super K, ? super Executor,
52
      ? extends CompletableFuture<? extends V>> mappingFunction;
53
  final AsyncCacheLoader<K, V> cacheLoader;
54

55
  @Nullable LoadingCacheView<K, V> cacheView;
56

57
  @SuppressWarnings("unchecked")
58
  LocalAsyncLoadingCache(AsyncCacheLoader<? super K, V> cacheLoader) {
1 ✔
59
    this.bulkMappingFunction = newBulkMappingFunction(cacheLoader);
1 ✔
60
    this.cacheLoader = (AsyncCacheLoader<K, V>) cacheLoader;
1 ✔
61
    this.mappingFunction = newMappingFunction(cacheLoader);
1 ✔
62
  }
1 ✔
63

64
  /** Returns a mapping function that adapts to {@link AsyncCacheLoader#asyncLoad}. */
65
  BiFunction<
66
      ? super K,
67
      ? super Executor,
68
      ? extends CompletableFuture<? extends V>> newMappingFunction(
69
          AsyncCacheLoader<? super K, V> cacheLoader) {
70
    return (key, executor) -> {
1 ✔
71
      try {
72
        return cacheLoader.asyncLoad(key, executor);
1 ✔
73
      } catch (Exception e) {
1 ✔
74
        throw toUnchecked(e);
1 ✔
75
      }
76
    };
77
  }
78

79
  /**
80
   * Returns a mapping function that adapts to {@link AsyncCacheLoader#asyncLoadAll}, if
81
   * implemented.
82
   */
83
  @Nullable BiFunction<Set<? extends K>, Executor, CompletableFuture<Map<K, V>>>
84
      newBulkMappingFunction(AsyncCacheLoader<? super K, V> cacheLoader) {
85
    if (!canBulkLoad(cacheLoader)) {
1 ✔
86
      return null;
1 ✔
87
    }
88
    return (keysToLoad, executor) -> {
1 ✔
89
      try {
90
        @SuppressWarnings("unchecked")
91
        var loaded = (CompletableFuture<Map<K, V>>) cacheLoader.asyncLoadAll(keysToLoad, executor);
1 ✔
92
        return loaded;
1 ✔
93
      } catch (Exception e) {
1 ✔
94
        throw toUnchecked(e);
1 ✔
95
      }
96
    };
97
  }
98

99
  /** Returns whether the supplied cache loader has bulk load functionality. */
100
  boolean canBulkLoad(AsyncCacheLoader<?, ?> loader) {
101
    @Var Class<?> defaultLoaderClass = AsyncCacheLoader.class;
1 ✔
102
    if (loader instanceof CacheLoader<?, ?>) {
1 ✔
103
      defaultLoaderClass = CacheLoader.class;
1 ✔
104
      if (hasMethodOverride(defaultLoaderClass, loader, "loadAll", Set.class)) {
1 ✔
105
        return true;
1 ✔
106
      }
107
    }
108
    return hasMethodOverride(defaultLoaderClass,
1 ✔
109
        loader, "asyncLoadAll", Set.class, Executor.class);
110
  }
111

112
  @Override
113
  public CompletableFuture<V> get(K key) {
114
    return get(key, mappingFunction);
1 ✔
115
  }
116

117
  @Override
118
  public CompletableFuture<Map<K, V>> getAll(Iterable<? extends K> keys) {
119
    if (bulkMappingFunction != null) {
1 ✔
120
      return getAll(keys, bulkMappingFunction);
1 ✔
121
    }
122

123
    int initialCapacity = calculateHashMapCapacity(keys);
1 ✔
124
    var result = new LinkedHashMap<K, @Nullable CompletableFuture<@Nullable V>>(initialCapacity);
1 ✔
125
    for (K key : keys) {
1 ✔
126
      result.put(requireNonNull(key), null);
1 ✔
127
    }
1 ✔
128
    for (var entry : result.entrySet()) {
1 ✔
129
      @SuppressWarnings("NullAway")
130
      CompletableFuture<@Nullable V> castedFuture = get(entry.getKey());
1 ✔
131
      entry.setValue(castedFuture);
1 ✔
132
    }
1 ✔
133

134
    @SuppressWarnings("NullAway")
135
    Map<K, CompletableFuture<@Nullable V>> results = result;
1 ✔
136
    return composeResult(results);
1 ✔
137
  }
138

139
  @Override
140
  public LoadingCache<K, V> synchronous() {
141
    var cv = cacheView;
1 ✔
142
    return (cv == null) ? (cacheView = new LoadingCacheView<>(this)) : cv;
1 ✔
143
  }
144

145
  /* --------------- Synchronous views --------------- */
146

147
  static final class LoadingCacheView<K, V>
148
      extends AbstractCacheView<K, V> implements LoadingCache<K, V> {
149
    private static final long serialVersionUID = 1L;
150

151
    @SuppressWarnings("serial")
152
    final LocalAsyncLoadingCache<K, V> asyncCache;
153

154
    LoadingCacheView(LocalAsyncLoadingCache<K, V> asyncCache) {
1 ✔
155
      this.asyncCache = requireNonNull(asyncCache);
1 ✔
156
    }
1 ✔
157

158
    @Override
159
    LocalAsyncLoadingCache<K, V> asyncCache() {
160
      return asyncCache;
1 ✔
161
    }
162

163
    @Override
164
    public V get(K key) {
165
      return resolve(asyncCache.get(key));
1 ✔
166
    }
167

168
    @Override
169
    public Map<K, V> getAll(Iterable<? extends K> keys) {
170
      return resolve(asyncCache.getAll(keys));
1 ✔
171
    }
172

173
    @Override
174
    public CompletableFuture<V> refresh(K key) {
175
      requireNonNull(key);
1 ✔
176

177
      Object keyReference = asyncCache.cache().referenceKey(key);
1 ✔
178
      for (;;) {
179
        @Var var future = tryOptimisticRefresh(key, keyReference);
1 ✔
180
        if (future == null) {
1 ✔
181
          future = tryComputeRefresh(key, keyReference);
1 ✔
182
        }
183
        if (future != null) {
1 ✔
184
          return future;
1 ✔
185
        }
186
      }
1 ✔
187
    }
188

189
    @Override
190
    public CompletableFuture<Map<K, V>> refreshAll(Iterable<? extends K> keys) {
191
      var result = new LinkedHashMap<K, CompletableFuture<V>>(
1 ✔
192
          calculateHashMapCapacity(keys));
1 ✔
193
      for (K key : keys) {
1 ✔
194
        result.computeIfAbsent(key, this::refresh);
1 ✔
195
      }
1 ✔
196
      @SuppressWarnings("NullAway")
197
      Map<K, CompletableFuture<@Nullable V>> futures = result;
1 ✔
198
      return composeResult(futures);
1 ✔
199
    }
200

201
    /** Attempts to avoid a reload if the entry is absent, or a load or reload is in-flight. */
202
    @SuppressWarnings("FutureReturnValueIgnored")
203
    private @Nullable CompletableFuture<V> tryOptimisticRefresh(K key, Object keyReference) {
204
      // If a refresh is registered, including one that completed but has not committed, then
205
      // return it directly. If the entry is pending eviction, then remove it to trigger a new load.
206
      var lastRefresh = asyncCache.cache().refreshes().get(keyReference);
1 ✔
207
      if (lastRefresh != null) {
1 ✔
208
        if (asyncCache.cache().isPendingEviction(key)) {
1 ✔
209
          asyncCache.cache().refreshes().remove(keyReference, lastRefresh);
1 ✔
210
        } else {
211
          return coalesce(lastRefresh);
1 ✔
212
        }
213
      }
214

215
      // If the entry is absent then perform a new load, else if in-flight then return it. A
216
      // completed future holding no value is a mapping whose removal has not been applied yet and
217
      // the slow path cannot act on it, so it is treated as absent.
218
      var oldValueFuture = asyncCache.cache().getIfPresentQuietly(key);
1 ✔
219
      if ((oldValueFuture == null) || (oldValueFuture.isDone() && !Async.isReady(oldValueFuture))) {
1 ✔
220
        if (oldValueFuture != null) {
1 ✔
221
          asyncCache.cache().remove(key, oldValueFuture);
1 ✔
222
        }
223
        var future = asyncCache.get(key, asyncCache.mappingFunction, /* recordStats= */ false);
1 ✔
224
        var prior = asyncCache.cache().refreshes().putIfAbsent(keyReference, future);
1 ✔
225
        if (prior != null) {
1 ✔
226
          return coalesce(prior);
1 ✔
227
        }
228
        future.whenComplete((r, e) -> asyncCache.cache().refreshes().remove(keyReference, future));
1 ✔
229
        return future;
1 ✔
230
      } else if (!oldValueFuture.isDone()) {
1 ✔
231
        // no-op if load is pending
232
        return oldValueFuture;
1 ✔
233
      }
234

235
      // Fallback to the slow path, possibly retrying
236
      return null;
1 ✔
237
    }
238

239
    /** Begins a refresh if the entry has materialized and no reload is in-flight. */
240
    @SuppressWarnings("FutureReturnValueIgnored")
241
    private @Nullable CompletableFuture<V> tryComputeRefresh(K key, Object keyReference) {
242
      @SuppressWarnings({"rawtypes", "unchecked"})
243
      @Nullable CompletableFuture<V>[] oldValueFuture = new CompletableFuture[1];
1 ✔
244
      @SuppressWarnings({"unchecked", "Varifier"})
245
      @Nullable V[] oldValue = (V[]) new Object[1];
1 ✔
246
      var pending = new LocalLoadingCache.PendingRefresh();
1 ✔
247
      var registered = asyncCache.cache().refreshes().computeIfAbsent(keyReference, k -> {
1 ✔
248
        oldValueFuture[0] = asyncCache.cache().getIfPresentQuietly(key);
1 ✔
249
        oldValue[0] = Async.getIfReady(oldValueFuture[0]);
1 ✔
250
        return (oldValue[0] == null) ? null : pending;
1 ✔
251
      });
252
      if (registered == null) {
1 ✔
253
        // Retry the optimistic path
254
        return null;
1 ✔
255
      } else if (registered != pending) {
1 !
UNCOV
256
        return coalesce(registered);
×
257
      }
258

259
      // The registration is published before the loader is called, so the loader runs outside the
260
      // refresh map's bin
261
      long startTime = asyncCache.cache().statsTicker().read();
1 ✔
262
      CompletableFuture<V> castedFuture;
263
      try {
264
        var reloadFuture = asyncCache.cacheLoader.asyncReload(
1 ✔
265
            key, requireNonNull(oldValue[0]), asyncCache.cache().executor());
1 ✔
266
        @SuppressWarnings("unchecked")
267
        var reloading = (CompletableFuture<V>) requireNonNull(reloadFuture, "Null future");
1 ✔
268
        castedFuture = reloading;
1 ✔
269
      } catch (Throwable t) {
1 ✔
270
        pending.withdraw(asyncCache.cache().refreshes(), keyReference, t);
1 ✔
271
        throw toUnchecked(t);
1 ✔
272
      }
1 ✔
273

274
      pending.publish(asyncCache.cache().refreshes(), keyReference, castedFuture);
1 ✔
275
      castedFuture.whenComplete((newValue, error) -> {
1 ✔
276
        long loadTime = asyncCache.cache().statsTicker().read() - startTime;
1 ✔
277
        if (error != null) {
1 ✔
278
          if (!(error instanceof CancellationException) && !(error instanceof TimeoutException)) {
1 ✔
279
            logger.log(Level.WARNING, "Exception thrown during refresh", error);
1 ✔
280
          }
281
          asyncCache.cache().refreshes().remove(keyReference, castedFuture);
1 ✔
282
          asyncCache.cache().statsCounter().recordLoadFailure(loadTime);
1 ✔
283
          return;
1 ✔
284
        }
285

286
        try {
287
          var discard = new boolean[1];
1 ✔
288
          var hints = new LocalCache.RemapHints();
1 ✔
289
          var value = asyncCache.cache().compute(key, (ignored, currentValue) -> {
1 ✔
290
            // Keep the refresh registered until the write clears it to avoid refreshAfterWrite
291
            // readers from prematurely scheduling another reload
292
            boolean successful =
1 ✔
293
                (asyncCache.cache().refreshes().get(keyReference) == castedFuture);
1 ✔
294
            if (successful && (currentValue == oldValueFuture[0])) {
1 ✔
295
              return (newValue == null) ? null : castedFuture;
1 ✔
296
            }
297
            // Otherwise, a write invalidated the refresh so discard it. If a successor refresh
298
            // owns the registration, leave it intact so this stale completion's by-key discard
299
            // cannot steal the successor's token (its fresh value would then be discarded).
300
            hints.preserveTimestamps = true;
1 ✔
301
            hints.preserveRefresh = !successful;
1 ✔
302
            discard[0] = (newValue != Async.getIfReady((CompletableFuture<?>) currentValue));
1 ✔
303
            return currentValue;
1 ✔
304
          }, asyncCache.cache().expiry(), /* recordLoad= */ false, hints);
1 ✔
305

306
          if (discard[0] && (newValue != null)) {
1 ✔
307
            var cause = (value == null) ? RemovalCause.EXPLICIT : RemovalCause.REPLACED;
1 ✔
308
            asyncCache.cache().notifyRemoval(key, castedFuture, cause);
1 ✔
309
          }
310
          if (newValue == null) {
1 ✔
311
            asyncCache.cache().statsCounter().recordLoadFailure(loadTime);
1 ✔
312
          } else {
313
            asyncCache.cache().statsCounter().recordLoadSuccess(loadTime);
1 ✔
314
          }
315
        } catch (Throwable t) {
1 ✔
316
          logger.log(Level.WARNING, "Exception thrown during refresh", t);
1 ✔
317
          asyncCache.cache().refreshes().remove(keyReference, castedFuture);
1 ✔
318
          asyncCache.cache().statsCounter().recordLoadFailure(loadTime);
1 ✔
319
          asyncCache.cache().remove(key, castedFuture);
1 ✔
320
        }
1 ✔
321
      });
1 ✔
322
      return castedFuture;
1 ✔
323
    }
324

325
    /** Returns the registered refresh's future, waiting for a pending registration's loader. */
326
    @SuppressWarnings("unchecked")
327
    private CompletableFuture<V> coalesce(CompletableFuture<?> registered) {
328
      return (CompletableFuture<V>) LocalLoadingCache.PendingRefresh.resolve(registered);
1 ✔
329
    }
330
  }
331
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc