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

ben-manes / caffeine / #5856

29 Nov 2026 10:35PM UTC coverage: 99.989% (-0.01%) from 100.0%
#5856

push

github

ben-manes
remove unnecessary allocations

4938 of 4938 branches covered (100.0%)

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

1 existing line in 1 file now uncovered.

9390 of 9391 relevant lines covered (99.99%)

1.0 hits per line

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

99.83
/caffeine/src/main/java/com/github/benmanes/caffeine/cache/UnboundedLocalCache.java
1
/*
2
 * Copyright 2014 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.LocalLoadingCache.newBulkMappingFunction;
19
import static com.github.benmanes.caffeine.cache.LocalLoadingCache.newMappingFunction;
20
import static java.lang.invoke.ConstantBootstraps.fieldVarHandle;
21
import static java.util.Objects.requireNonNull;
22

23
import java.io.InvalidObjectException;
24
import java.io.ObjectInputStream;
25
import java.io.Serializable;
26
import java.lang.System.Logger;
27
import java.lang.System.Logger.Level;
28
import java.lang.invoke.MethodHandles;
29
import java.lang.invoke.VarHandle;
30
import java.util.AbstractCollection;
31
import java.util.AbstractSet;
32
import java.util.ArrayList;
33
import java.util.Collection;
34
import java.util.Collections;
35
import java.util.HashMap;
36
import java.util.Iterator;
37
import java.util.Map;
38
import java.util.Objects;
39
import java.util.Optional;
40
import java.util.Set;
41
import java.util.Spliterator;
42
import java.util.concurrent.CompletableFuture;
43
import java.util.concurrent.ConcurrentHashMap;
44
import java.util.concurrent.ConcurrentMap;
45
import java.util.concurrent.Executor;
46
import java.util.function.BiConsumer;
47
import java.util.function.BiFunction;
48
import java.util.function.Consumer;
49
import java.util.function.Function;
50
import java.util.function.Predicate;
51

52
import org.jspecify.annotations.Nullable;
53

54
import com.github.benmanes.caffeine.cache.stats.StatsCounter;
55
import com.google.errorprone.annotations.CanIgnoreReturnValue;
56
import com.google.errorprone.annotations.Var;
57

58
/**
59
 * An in-memory cache that has no capabilities for bounding the map. This implementation provides
60
 * a lightweight wrapper on top of {@link ConcurrentHashMap}.
61
 *
62
 * @author ben.manes@gmail.com (Ben Manes)
63
 */
64
@SuppressWarnings("serial")
65
final class UnboundedLocalCache<K, V> implements LocalCache<K, V> {
66
  static final Logger logger = System.getLogger(UnboundedLocalCache.class.getName());
1 ✔
67
  static final VarHandle REFRESHES = fieldVarHandle(MethodHandles.lookup(),
1 ✔
68
      "refreshes", VarHandle.class, UnboundedLocalCache.class, ConcurrentMap.class);
69

70
  final @Nullable RemovalListener<K, V> removalListener;
71
  final ConcurrentHashMap<K, V> data;
72
  final StatsCounter statsCounter;
73
  final boolean isRecordingStats;
74
  final Executor executor;
75
  final boolean isAsync;
76

77
  @Nullable Set<K> keySet;
78
  @Nullable Collection<V> values;
79
  @Nullable Set<Entry<K, V>> entrySet;
80
  volatile @Nullable ConcurrentMap<Object, CompletableFuture<?>> refreshes;
81

82
  UnboundedLocalCache(Caffeine<? super K, ? super V> builder, boolean isAsync) {
1 ✔
83
    this.data = new ConcurrentHashMap<>(builder.getInitialCapacity());
1 ✔
84
    this.statsCounter = builder.getStatsCounterSupplier().get();
1 ✔
85
    this.removalListener = builder.getRemovalListener(isAsync);
1 ✔
86
    this.isRecordingStats = builder.isRecordingStats();
1 ✔
87
    this.executor = builder.getExecutor();
1 ✔
88
    this.isAsync = isAsync;
1 ✔
89
  }
1 ✔
90

91
  @Override
92
  public boolean isAsync() {
93
    return isAsync;
1 ✔
94
  }
95

96
  @Override
97
  public @Nullable RemovalListener<K, V> removalListener() {
98
    return removalListener;
1 ✔
99
  }
100

101
  @Override
102
  public @Nullable Expiry<K, V> expiry() {
103
    return null;
1 ✔
104
  }
105

106
  @Override
107
  public boolean collectKeys() {
108
    return false;
1 ✔
109
  }
110

111
  @Override
112
  @CanIgnoreReturnValue
113
  public Object referenceKey(K key) {
114
    return key;
1 ✔
115
  }
116

117
  @Override
118
  public boolean isPendingEviction(K key) {
119
    return false;
1 ✔
120
  }
121

122
  /* --------------- Cache --------------- */
123

124
  @Override
125
  @SuppressWarnings("SuspiciousMethodCalls")
126
  public @Nullable V getIfPresent(Object key, boolean recordStats) {
127
    V value = data.get(key);
1 ✔
128

129
    if (recordStats) {
1 ✔
130
      if (value == null) {
1 ✔
131
        statsCounter.recordMisses(1);
1 ✔
132
      } else {
133
        statsCounter.recordHits(1);
1 ✔
134
      }
135
    }
136
    return value;
1 ✔
137
  }
138

139
  @Override
140
  @SuppressWarnings("SuspiciousMethodCalls")
141
  public @Nullable V getIfPresentQuietly(Object key) {
142
    return data.get(key);
1 ✔
143
  }
144

145
  @Override
146
  public long estimatedSize() {
147
    return data.mappingCount();
1 ✔
148
  }
149

150
  @Override
151
  public int getAllPresent(Map<K, @Nullable V> result, boolean retainAbsent) {
152
    @Var int absent = 0;
1 ✔
153
    int uniqueKeys = result.size();
1 ✔
154
    for (var iter = result.entrySet().iterator(); iter.hasNext();) {
1 ✔
155
      Map.Entry<K, @Nullable V> entry = iter.next();
1 ✔
156
      V value = data.get(entry.getKey());
1 ✔
157
      if (value != null) {
1 ✔
158
        entry.setValue(value);
1 ✔
159
        continue;
1 ✔
160
      }
161
      absent++;
1 ✔
162
      if (!retainAbsent) {
1 ✔
163
        iter.remove();
1 ✔
164
      }
165
    }
1 ✔
166
    statsCounter.recordHits(uniqueKeys - absent);
1 ✔
167
    statsCounter.recordMisses(absent);
1 ✔
168
    return absent;
1 ✔
169
  }
170

171
  @Override
172
  public void cleanUp() {}
1 ✔
173

174
  @Override
175
  public StatsCounter statsCounter() {
176
    return statsCounter;
1 ✔
177
  }
178

179
  @Override
180
  @SuppressWarnings("PMD.AvoidInstanceofChecksInCatchClause")
181
  public void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause) {
182
    var removalListener = removalListener();
1 ✔
183
    if (removalListener == null) {
1 ✔
184
      return;
1 ✔
185
    }
186
    Runnable task = () -> {
1 ✔
187
      try {
188
        removalListener.onRemoval(key, value, cause);
1 ✔
189
      } catch (Throwable t) {
1 ✔
190
        if (t instanceof InterruptedException) {
1 ✔
191
          Thread.currentThread().interrupt();
1 ✔
192
        }
193
        logger.log(Level.WARNING, "Exception thrown by removal listener", t);
1 ✔
194
      }
1 ✔
195
    };
1 ✔
196
    try {
197
      executor.execute(task);
1 ✔
198
    } catch (Throwable t) {
1 ✔
199
      logger.log(Level.ERROR, "Exception thrown when submitting removal listener", t);
1 ✔
200
      task.run();
1 ✔
201
    }
1 ✔
202
  }
1 ✔
203

204
  @Override
205
  public boolean isRecordingStats() {
206
    return isRecordingStats;
1 ✔
207
  }
208

209
  @Override
210
  public Executor executor() {
211
    return executor;
1 ✔
212
  }
213

214
  @Override
215
  public ConcurrentMap<Object, CompletableFuture<?>> refreshes() {
216
    @Var var pending = refreshes;
1 ✔
217
    if (pending == null) {
1 ✔
218
      pending = new ConcurrentHashMap<>();
1 ✔
219
      if (!REFRESHES.compareAndSet(this, null, pending)) {
1 ✔
UNCOV
220
        pending = requireNonNull(refreshes);
×
221
      }
222
    }
223
    return pending;
1 ✔
224
  }
225

226
  /** Invalidate the in-flight refresh. */
227
  void discardRefresh(Object keyReference) {
228
    var pending = refreshes;
1 ✔
229
    if (pending != null) {
1 ✔
230
      pending.remove(keyReference);
1 ✔
231
    }
232
  }
1 ✔
233

234
  @Override
235
  public Ticker statsTicker() {
236
    return isRecordingStats ? Ticker.systemTicker() : Ticker.disabledTicker();
1 ✔
237
  }
238

239
  /* --------------- JDK8+ Map extensions --------------- */
240

241
  @Override
242
  public void forEach(BiConsumer<? super K, ? super V> action) {
243
    data.forEach(action);
1 ✔
244
  }
1 ✔
245

246
  @Override
247
  @SuppressWarnings("ResultOfMethodCallIgnored")
248
  public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
249
    requireNonNull(function);
1 ✔
250

251
    BiFunction<K, @Nullable V, @Nullable V> remappingFunction = (key, oldValue) ->
1 ✔
252
        requireNonNull(function.apply(key, requireNonNull(oldValue)));
1 ✔
253
    for (K key : data.keySet()) {
1 ✔
254
      remap(key, remappingFunction, /* hints= */ null, /* computeIfAbsent= */ false);
1 ✔
255
    }
1 ✔
256
  }
1 ✔
257

258
  @Override
259
  public @Nullable V computeIfAbsent(K key,
260
      Function<? super K, ? extends @Nullable V> mappingFunction,
261
      boolean recordStats, boolean recordLoad) {
262
    requireNonNull(mappingFunction);
1 ✔
263

264
    // An optimistic fast path to avoid unnecessary locking
265
    @Var V value = data.get(key);
1 ✔
266
    if (value != null) {
1 ✔
267
      if (recordStats) {
1 ✔
268
        statsCounter.recordHits(1);
1 ✔
269
      }
270
      return value;
1 ✔
271
    }
272

273
    boolean[] missed = new boolean[1];
1 ✔
274
    value = data.computeIfAbsent(key, k -> {
1 ✔
275
      missed[0] = true;
1 ✔
276
      V computed = recordStats
1 ✔
277
          ? statsAware(mappingFunction, recordLoad).apply(k)
1 ✔
278
          : mappingFunction.apply(k);
1 ✔
279
      discardRefresh(k);
1 ✔
280
      return computed;
1 ✔
281
    });
282
    if (!missed[0] && recordStats) {
1 ✔
283
      statsCounter.recordHits(1);
1 ✔
284
    }
285
    return value;
1 ✔
286
  }
287

288
  @Override
289
  public @Nullable V computeIfPresent(K key,
290
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction) {
291
    requireNonNull(remappingFunction);
1 ✔
292

293
    // An optimistic fast path to avoid unnecessary locking
294
    if (!data.containsKey(key)) {
1 ✔
295
      return null;
1 ✔
296
    }
297

298
    // ensures that the removal notification is processed after the removal has completed
299
    @SuppressWarnings({"unchecked", "Varifier"})
300
    @Nullable V[] oldValue = (V[]) new Object[1];
1 ✔
301
    V nv = data.computeIfPresent(key, (K k, V value) -> {
1 ✔
302
      BiFunction<? super K, ? super V, ? extends @Nullable V> function = statsAware(
1 ✔
303
          remappingFunction, /* recordLoad= */ true);
304
      try {
305
        V newValue = function.apply(k, value);
1 ✔
306
        if (newValue != value) {
1 ✔
307
          oldValue[0] = value;
1 ✔
308
        }
309

310
        discardRefresh(k);
1 ✔
311
        return newValue;
1 ✔
312
      } catch (Throwable t) {
1 ✔
313
        discardRefresh(k);
1 ✔
314
        throw t;
1 ✔
315
      }
316
    });
317
    if (nv != null) {
1 ✔
318
      notifyOnReplace(key, oldValue[0], nv);
1 ✔
319
    } else if (oldValue[0] != null) {
1 ✔
320
      notifyRemoval(key, oldValue[0], RemovalCause.EXPLICIT);
1 ✔
321
    }
322
    return nv;
1 ✔
323
  }
324

325
  @Override
326
  public @Nullable V compute(K key,
327
      BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
328
      @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad,
329
      @Nullable RemapHints hints) {
330
    requireNonNull(remappingFunction);
1 ✔
331
    return remap(key, statsAware(remappingFunction, recordLoad),
1 ✔
332
        hints, /* computeIfAbsent= */ true);
333
  }
334

335
  @Override
336
  public @Nullable V merge(K key, V value,
337
      BiFunction<? super V, ? super V, ? extends @Nullable V> remappingFunction) {
338
    requireNonNull(remappingFunction);
1 ✔
339
    requireNonNull(value);
1 ✔
340

341
    return remap(key, (K k, @Nullable V oldValue) ->
1 ✔
342
      (oldValue == null) ? value : statsAware(remappingFunction).apply(oldValue, value),
1 ✔
343
      /* hints= */ null, /* computeIfAbsent= */ true);
344
  }
345

346
  /**
347
   * A {@link Map#compute(Object, BiFunction)} that does not directly record any cache statistics.
348
   *
349
   * @param key key with which the specified value is to be associated
350
   * @param remappingFunction the function to compute a value
351
   * @param hints flags from a query-style caller, or {@code null} if not present
352
   * @param computeIfAbsent whether the caller may create an entry when the key is absent
353
   * @return the new value associated with the specified key, or null if none
354
   */
355
  @Nullable V remap(K key,
356
      BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
357
      @Nullable RemapHints hints, boolean computeIfAbsent) {
358
    // ensures that the removal notification is processed after the removal has completed
359
    @SuppressWarnings({"unchecked", "Varifier"})
360
    @Nullable V[] oldValue = (@Nullable V[]) new Object[1];
1 ✔
361
    V nv = data.compute(key, (K k, @Nullable V value) -> {
1 ✔
362
      if ((value == null) && !computeIfAbsent) {
1 ✔
363
        return null;
1 ✔
364
      }
365
      try {
366
        V newValue = remappingFunction.apply(k, value);
1 ✔
367
        if ((value == null) && (newValue == null)) {
1 ✔
368
          // A stale refresh whose entry is absent leaves a successor's registration intact
369
          if ((hints == null) || !hints.preserveRefresh) {
1 ✔
370
            discardRefresh(k);
1 ✔
371
          }
372
          return null;
1 ✔
373
        }
374

375
        if (newValue != value) {
1 ✔
376
          oldValue[0] = value;
1 ✔
377
        }
378

379
        // A query-style caller may flag a same-instance return as a no-op that must leave any
380
        // in-flight refresh intact whereas a real mutation discards a racing refresh so that a
381
        // stale reload cannot overwrite the new mapping.
382
        boolean preserveRefresh = (hints != null) && hints.preserveRefresh && (newValue == value);
1 ✔
383
        if (!preserveRefresh) {
1 ✔
384
          discardRefresh(k);
1 ✔
385
        }
386
        return newValue;
1 ✔
387
      } catch (Throwable t) {
1 ✔
388
        if (value != null) {
1 ✔
389
          discardRefresh(k);
1 ✔
390
        }
391
        throw t;
1 ✔
392
      }
393
    });
394
    if (nv != null) {
1 ✔
395
      notifyOnReplace(key, oldValue[0], nv);
1 ✔
396
    } else if (oldValue[0] != null) {
1 ✔
397
      notifyRemoval(key, oldValue[0], RemovalCause.EXPLICIT);
1 ✔
398
    }
399
    return nv;
1 ✔
400
  }
401

402
  /* --------------- Concurrent Map --------------- */
403

404
  @Override
405
  public boolean isEmpty() {
406
    return data.isEmpty();
1 ✔
407
  }
408

409
  @Override
410
  public int size() {
411
    return data.size();
1 ✔
412
  }
413

414
  @Override
415
  @SuppressWarnings("ResultOfMethodCallIgnored")
416
  public void clear() {
417
    var pending = refreshes;
1 ✔
418
    if (pending != null) {
1 ✔
419
      pending.clear();
1 ✔
420
    }
421

422
    var keys = (removalListener == null) ? data.keySet() : new ArrayList<>(data.keySet());
1 ✔
423
    for (K key : keys) {
1 ✔
424
      remove(key);
1 ✔
425
    }
1 ✔
426
  }
1 ✔
427

428
  @Override
429
  public boolean containsKey(@Nullable Object key) {
430
    requireNonNull(key);
1 ✔
431
    return data.containsKey(key);
1 ✔
432
  }
433

434
  @Override
435
  public boolean containsValue(@Nullable Object value) {
436
    requireNonNull(value);
1 ✔
437
    return data.containsValue(value);
1 ✔
438
  }
439

440
  @Override
441
  public @Nullable V get(@Nullable Object key) {
442
    requireNonNull(key);
1 ✔
443
    return getIfPresent(key, /* recordStats= */ false);
1 ✔
444
  }
445

446
  @Override
447
  public @Nullable V put(K key, V value) {
448
    requireNonNull(value);
1 ✔
449

450
    @SuppressWarnings({"unchecked", "Varifier"})
451
    @Nullable V[] oldValue = (@Nullable V[]) new Object[1];
1 ✔
452
    data.compute(key, (K k, @Nullable V v) -> {
1 ✔
453
      discardRefresh(k);
1 ✔
454
      oldValue[0] = v;
1 ✔
455
      return value;
1 ✔
456
    });
457
    if (oldValue[0] != null) {
1 ✔
458
      notifyOnReplace(key, oldValue[0], value);
1 ✔
459
    }
460
    return oldValue[0];
1 ✔
461
  }
462

463
  @Override
464
  public @Nullable V putIfAbsent(K key, V value) {
465
    requireNonNull(value);
1 ✔
466

467
    // An optimistic fast path to avoid unnecessary locking
468
    var v = data.get(key);
1 ✔
469
    if (v != null) {
1 ✔
470
      return v;
1 ✔
471
    }
472

473
    var added = new boolean[1];
1 ✔
474
    var val = data.computeIfAbsent(key, k -> {
1 ✔
475
      discardRefresh(k);
1 ✔
476
      added[0] = true;
1 ✔
477
      return value;
1 ✔
478
    });
479
    return added[0] ? null : val;
1 ✔
480
  }
481

482
  @Override
483
  @SuppressWarnings("ResultOfMethodCallIgnored")
484
  public void putAll(Map<? extends K, ? extends V> map) {
485
    map.forEach(this::put);
1 ✔
486
  }
1 ✔
487

488
  @Override
489
  public @Nullable V remove(@Nullable Object key) {
490
    requireNonNull(key);
1 ✔
491

492
    @SuppressWarnings("unchecked")
493
    var castKey = (K) key;
1 ✔
494
    @SuppressWarnings({"unchecked", "Varifier"})
495
    @Nullable V[] oldValue = (V[]) new Object[1];
1 ✔
496
    data.compute(castKey, (k, v) -> {
1 ✔
497
      discardRefresh(k);
1 ✔
498
      oldValue[0] = v;
1 ✔
499
      return null;
1 ✔
500
    });
501

502
    if (oldValue[0] != null) {
1 ✔
503
      notifyRemoval(castKey, oldValue[0], RemovalCause.EXPLICIT);
1 ✔
504
    }
505

506
    return oldValue[0];
1 ✔
507
  }
508

509
  @Override
510
  public boolean remove(@Nullable Object key, @Nullable Object value) {
511
    requireNonNull(key);
1 ✔
512
    if (value == null) {
1 ✔
513
      return false;
1 ✔
514
    }
515

516
    @SuppressWarnings("unchecked")
517
    var castKey = (K) key;
1 ✔
518
    @SuppressWarnings({"unchecked", "Varifier"})
519
    @Nullable V[] oldValue = (V[]) new Object[1];
1 ✔
520

521
    data.computeIfPresent(castKey, (k, v) -> {
1 ✔
522
      if (Objects.equals(value, v)) {
1 ✔
523
        discardRefresh(k);
1 ✔
524
        oldValue[0] = v;
1 ✔
525
        return null;
1 ✔
526
      }
527
      return v;
1 ✔
528
    });
529

530
    if (oldValue[0] != null) {
1 ✔
531
      notifyRemoval(castKey, oldValue[0], RemovalCause.EXPLICIT);
1 ✔
532
      return true;
1 ✔
533
    }
534
    return false;
1 ✔
535
  }
536

537
  @Override
538
  public @Nullable V replace(K key, V value) {
539
    requireNonNull(value);
1 ✔
540

541
    @SuppressWarnings({"unchecked", "Varifier"})
542
    @Nullable V[] oldValue = (@Nullable V[]) new Object[1];
1 ✔
543
    data.computeIfPresent(key, (k, v) -> {
1 ✔
544
      discardRefresh(k);
1 ✔
545
      oldValue[0] = v;
1 ✔
546
      return value;
1 ✔
547
    });
548

549
    notifyOnReplace(key, oldValue[0], value);
1 ✔
550
    return oldValue[0];
1 ✔
551
  }
552

553
  @Override
554
  public boolean replace(K key, V oldValue, V newValue,
555
      boolean shouldDiscardRefresh, boolean quietly) {
556
    requireNonNull(oldValue);
1 ✔
557
    requireNonNull(newValue);
1 ✔
558

559
    @SuppressWarnings({"unchecked", "Varifier"})
560
    @Nullable V[] prev = (V[]) new Object[1];
1 ✔
561
    data.computeIfPresent(key, (k, v) -> {
1 ✔
562
      if (Objects.equals(oldValue, v)) {
1 ✔
563
        if (shouldDiscardRefresh) {
1 ✔
564
          discardRefresh(k);
1 ✔
565
        }
566
        prev[0] = v;
1 ✔
567
        return newValue;
1 ✔
568
      }
569
      return v;
1 ✔
570
    });
571

572
    notifyOnReplace(key, prev[0], newValue);
1 ✔
573
    return (prev[0] != null);
1 ✔
574
  }
575

576
  @Override
577
  @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
578
  public boolean equals(@Nullable Object o) {
579
    if (o == this) {
1 ✔
580
      return true;
1 ✔
581
    }
582
    try {
583
      return data.equals(o);
1 ✔
584
    } catch (ClassCastException | NullPointerException ignored) {
1 ✔
585
      return false;
1 ✔
586
    }
587
  }
588

589
  @Override
590
  public int hashCode() {
591
    return data.hashCode();
1 ✔
592
  }
593

594
  @Override
595
  public String toString() {
596
    var result = new StringBuilder(50).append('{');
1 ✔
597
    data.forEach((key, value) -> {
1 ✔
598
      if (result.length() != 1) {
1 ✔
599
        result.append(", ");
1 ✔
600
      }
601
      result.append((key == this) ? "(this Map)" : key)
1 ✔
602
          .append('=')
1 ✔
603
          .append((value == this) ? "(this Map)" : value);
1 ✔
604
    });
1 ✔
605
    return result.append('}').toString();
1 ✔
606
  }
607

608
  @Override
609
  public Set<K> keySet() {
610
    Set<K> ks = keySet;
1 ✔
611
    return (ks == null) ? (keySet = new KeySetView<>(this)) : ks;
1 ✔
612
  }
613

614
  @Override
615
  public Collection<V> values() {
616
    Collection<V> vs = values;
1 ✔
617
    return (vs == null) ? (values = new ValuesView<>(this)) : vs;
1 ✔
618
  }
619

620
  @Override
621
  public Set<Entry<K, V>> entrySet() {
622
    Set<Entry<K, V>> es = entrySet;
1 ✔
623
    return (es == null) ? (entrySet = new EntrySetView<>(this)) : es;
1 ✔
624
  }
625

626
  /** An adapter to safely externalize the keys. */
627
  static final class KeySetView<K> extends AbstractSet<K> {
628
    final UnboundedLocalCache<K, ?> cache;
629

630
    KeySetView(UnboundedLocalCache<K, ?> cache) {
1 ✔
631
      this.cache = requireNonNull(cache);
1 ✔
632
    }
1 ✔
633

634
    @Override
635
    public boolean isEmpty() {
636
      return cache.isEmpty();
1 ✔
637
    }
638

639
    @Override
640
    public int size() {
641
      return cache.size();
1 ✔
642
    }
643

644
    @Override
645
    public void clear() {
646
      cache.clear();
1 ✔
647
    }
1 ✔
648

649
    @Override
650
    @SuppressWarnings("SuspiciousMethodCalls")
651
    public boolean contains(@Nullable Object o) {
652
      return cache.containsKey(o);
1 ✔
653
    }
654

655
    @Override
656
    public boolean containsAll(Collection<?> collection) {
657
      requireNonNull(collection);
1 ✔
658
      if (collection != this) {
1 ✔
659
        for (Object o : collection) {
1 ✔
660
          if ((o == null) || !contains(o)) {
1 ✔
661
            return false;
1 ✔
662
          }
663
        }
1 ✔
664
      }
665
      return true;
1 ✔
666
    }
667

668
    @Override
669
    public boolean removeAll(Collection<?> collection) {
670
      requireNonNull(collection);
1 ✔
671
      @Var boolean modified = false;
1 ✔
672
      if ((collection instanceof Set<?>) && (collection.size() > size())) {
1 ✔
673
        for (K key : this) {
1 ✔
674
          if (collection.contains(key)) {
1 ✔
675
            modified |= remove(key);
1 ✔
676
          }
677
        }
1 ✔
678
      } else {
679
        for (var o : collection) {
1 ✔
680
          modified |= (o != null) && remove(o);
1 ✔
681
        }
1 ✔
682
      }
683
      return modified;
1 ✔
684
    }
685

686
    @Override
687
    public boolean remove(@Nullable Object o) {
688
      return (cache.remove(o) != null);
1 ✔
689
    }
690

691
    @Override
692
    public boolean removeIf(Predicate<? super K> filter) {
693
      requireNonNull(filter);
1 ✔
694
      @Var boolean modified = false;
1 ✔
695
      for (K key : this) {
1 ✔
696
        if (filter.test(key) && remove(key)) {
1 ✔
697
          modified = true;
1 ✔
698
        }
699
      }
1 ✔
700
      return modified;
1 ✔
701
    }
702

703
    @Override
704
    public boolean retainAll(Collection<?> collection) {
705
      requireNonNull(collection);
1 ✔
706
      @Var boolean modified = false;
1 ✔
707
      for (K key : this) {
1 ✔
708
        if (!collection.contains(key) && remove(key)) {
1 ✔
709
          modified = true;
1 ✔
710
        }
711
      }
1 ✔
712
      return modified;
1 ✔
713
    }
714

715
    @Override
716
    public void forEach(Consumer<? super K> action) {
717
      cache.data.keySet().forEach(action);
1 ✔
718
    }
1 ✔
719

720
    @Override
721
    public Iterator<K> iterator() {
722
      return new KeyIterator<>(cache);
1 ✔
723
    }
724

725
    @Override
726
    public Spliterator<K> spliterator() {
727
      return new KeySpliterator<>(cache);
1 ✔
728
    }
729

730
    @Override
731
    public @Nullable Object[] toArray() {
732
      return cache.data.keySet().toArray();
1 ✔
733
    }
734

735
    @Override
736
    public <T extends @Nullable Object> T[] toArray(T[] array) {
737
      return cache.data.keySet().toArray(array);
1 ✔
738
    }
739
  }
740

741
  /** An adapter to safely externalize the key iterator. */
742
  static final class KeyIterator<K> implements Iterator<K> {
743
    final UnboundedLocalCache<K, ?> cache;
744
    final Iterator<K> iterator;
745
    @Nullable K current;
746

747
    KeyIterator(UnboundedLocalCache<K, ?> cache) {
1 ✔
748
      this.iterator = cache.data.keySet().iterator();
1 ✔
749
      this.cache = cache;
1 ✔
750
    }
1 ✔
751

752
    @Override
753
    public boolean hasNext() {
754
      return iterator.hasNext();
1 ✔
755
    }
756

757
    @Override
758
    public K next() {
759
      current = iterator.next();
1 ✔
760
      return current;
1 ✔
761
    }
762

763
    @Override
764
    @SuppressWarnings("ResultOfMethodCallIgnored")
765
    public void remove() {
766
      if (current == null) {
1 ✔
767
        throw new IllegalStateException();
1 ✔
768
      }
769
      cache.remove(current);
1 ✔
770
      current = null;
1 ✔
771
    }
1 ✔
772
  }
773

774
  /** An adapter to safely externalize the key spliterator. */
775
  static final class KeySpliterator<K> implements Spliterator<K> {
776
    final Spliterator<K> spliterator;
777

778
    KeySpliterator(UnboundedLocalCache<K, ?> cache) {
779
      this(cache.data.keySet().spliterator());
1 ✔
780
    }
1 ✔
781

782
    KeySpliterator(Spliterator<K> spliterator) {
1 ✔
783
      this.spliterator = requireNonNull(spliterator);
1 ✔
784
    }
1 ✔
785

786
    @Override
787
    public void forEachRemaining(Consumer<? super K> action) {
788
      requireNonNull(action);
1 ✔
789
      spliterator.forEachRemaining(action);
1 ✔
790
    }
1 ✔
791

792
    @Override
793
    public boolean tryAdvance(Consumer<? super K> action) {
794
      requireNonNull(action);
1 ✔
795
      return spliterator.tryAdvance(action);
1 ✔
796
    }
797

798
    @Override
799
    public @Nullable KeySpliterator<K> trySplit() {
800
      Spliterator<K> split = spliterator.trySplit();
1 ✔
801
      return (split == null) ? null : new KeySpliterator<>(split);
1 ✔
802
    }
803

804
    @Override
805
    public long estimateSize() {
806
      return spliterator.estimateSize();
1 ✔
807
    }
808

809
    @Override
810
    public int characteristics() {
811
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
812
    }
813
  }
814

815
  /** An adapter to safely externalize the values. */
816
  static final class ValuesView<K, V> extends AbstractCollection<V> {
817
    final UnboundedLocalCache<K, V> cache;
818

819
    ValuesView(UnboundedLocalCache<K, V> cache) {
1 ✔
820
      this.cache = requireNonNull(cache);
1 ✔
821
    }
1 ✔
822

823
    @Override
824
    public boolean isEmpty() {
825
      return cache.isEmpty();
1 ✔
826
    }
827

828
    @Override
829
    public int size() {
830
      return cache.size();
1 ✔
831
    }
832

833
    @Override
834
    public void clear() {
835
      cache.clear();
1 ✔
836
    }
1 ✔
837

838
    @Override
839
    @SuppressWarnings("SuspiciousMethodCalls")
840
    public boolean contains(@Nullable Object o) {
841
      return cache.containsValue(o);
1 ✔
842
    }
843

844
    @Override
845
    public boolean containsAll(Collection<?> collection) {
846
      requireNonNull(collection);
1 ✔
847
      if (collection != this) {
1 ✔
848
        for (Object o : collection) {
1 ✔
849
          if ((o == null) || !contains(o)) {
1 ✔
850
            return false;
1 ✔
851
          }
852
        }
1 ✔
853
      }
854
      return true;
1 ✔
855
    }
856

857
    @Override
858
    public boolean removeAll(Collection<?> collection) {
859
      requireNonNull(collection);
1 ✔
860
      @Var boolean modified = false;
1 ✔
861
      for (var entry : cache.data.entrySet()) {
1 ✔
862
        if (collection.contains(entry.getValue())
1 ✔
863
            && cache.remove(entry.getKey(), entry.getValue())) {
1 ✔
864
          modified = true;
1 ✔
865
        }
866
      }
1 ✔
867
      return modified;
1 ✔
868
    }
869

870
    @Override
871
    public boolean remove(@Nullable Object o) {
872
      if (o == null) {
1 ✔
873
        return false;
1 ✔
874
      }
875
      for (var entry : cache.data.entrySet()) {
1 ✔
876
        if (o.equals(entry.getValue()) && cache.remove(entry.getKey(), entry.getValue())) {
1 ✔
877
          return true;
1 ✔
878
        }
879
      }
1 ✔
880
      return false;
1 ✔
881
    }
882

883
    @Override
884
    public boolean removeIf(Predicate<? super V> filter) {
885
      requireNonNull(filter);
1 ✔
886
      @Var boolean removed = false;
1 ✔
887
      for (var entry : cache.data.entrySet()) {
1 ✔
888
        if (filter.test(entry.getValue())) {
1 ✔
889
          removed |= cache.remove(entry.getKey(), entry.getValue());
1 ✔
890
        }
891
      }
1 ✔
892
      return removed;
1 ✔
893
    }
894

895
    @Override
896
    public boolean retainAll(Collection<?> collection) {
897
      requireNonNull(collection);
1 ✔
898
      @Var boolean modified = false;
1 ✔
899
      for (var entry : cache.data.entrySet()) {
1 ✔
900
        if (!collection.contains(entry.getValue())
1 ✔
901
            && cache.remove(entry.getKey(), entry.getValue())) {
1 ✔
902
          modified = true;
1 ✔
903
        }
904
      }
1 ✔
905
      return modified;
1 ✔
906
    }
907

908
    @Override
909
    public void forEach(Consumer<? super V> action) {
910
      cache.data.values().forEach(action);
1 ✔
911
    }
1 ✔
912

913
    @Override
914
    public Iterator<V> iterator() {
915
      return new ValueIterator<>(cache);
1 ✔
916
    }
917

918
    @Override
919
    public Spliterator<V> spliterator() {
920
      return new ValueSpliterator<>(cache);
1 ✔
921
    }
922

923
    @Override
924
    public @Nullable Object[] toArray() {
925
      return cache.data.values().toArray();
1 ✔
926
    }
927

928
    @Override
929
    public <T extends @Nullable Object> T[] toArray(T[] array) {
930
      return cache.data.values().toArray(array);
1 ✔
931
    }
932
  }
933

934
  /** An adapter to safely externalize the value iterator. */
935
  static final class ValueIterator<K, V> implements Iterator<V> {
936
    final UnboundedLocalCache<K, V> cache;
937
    final Iterator<Entry<K, V>> iterator;
938
    @Nullable Entry<K, V> entry;
939

940
    ValueIterator(UnboundedLocalCache<K, V> cache) {
1 ✔
941
      this.iterator = cache.data.entrySet().iterator();
1 ✔
942
      this.cache = cache;
1 ✔
943
    }
1 ✔
944

945
    @Override
946
    public boolean hasNext() {
947
      return iterator.hasNext();
1 ✔
948
    }
949

950
    @Override
951
    public V next() {
952
      entry = iterator.next();
1 ✔
953
      return entry.getValue();
1 ✔
954
    }
955

956
    @Override
957
    @SuppressWarnings("ResultOfMethodCallIgnored")
958
    public void remove() {
959
      if (entry == null) {
1 ✔
960
        throw new IllegalStateException();
1 ✔
961
      }
962
      cache.remove(entry.getKey());
1 ✔
963
      entry = null;
1 ✔
964
    }
1 ✔
965
  }
966

967
  /** An adapter to safely externalize the value spliterator. */
968
  static final class ValueSpliterator<V> implements Spliterator<V> {
969
    final Spliterator<V> spliterator;
970

971
    ValueSpliterator(UnboundedLocalCache<?, V> cache) {
972
      this(cache.data.values().spliterator());
1 ✔
973
    }
1 ✔
974

975
    ValueSpliterator(Spliterator<V> spliterator) {
1 ✔
976
      this.spliterator = requireNonNull(spliterator);
1 ✔
977
    }
1 ✔
978

979
    @Override
980
    public void forEachRemaining(Consumer<? super V> action) {
981
      requireNonNull(action);
1 ✔
982
      spliterator.forEachRemaining(action);
1 ✔
983
    }
1 ✔
984

985
    @Override
986
    public boolean tryAdvance(Consumer<? super V> action) {
987
      requireNonNull(action);
1 ✔
988
      return spliterator.tryAdvance(action);
1 ✔
989
    }
990

991
    @Override
992
    public @Nullable ValueSpliterator<V> trySplit() {
993
      Spliterator<V> split = spliterator.trySplit();
1 ✔
994
      return (split == null) ? null : new ValueSpliterator<>(split);
1 ✔
995
    }
996

997
    @Override
998
    public long estimateSize() {
999
      return spliterator.estimateSize();
1 ✔
1000
    }
1001

1002
    @Override
1003
    public int characteristics() {
1004
      return CONCURRENT | NONNULL;
1 ✔
1005
    }
1006
  }
1007

1008
  /** An adapter to safely externalize the entries. */
1009
  static final class EntrySetView<K, V> extends AbstractSet<Entry<K, V>> {
1010
    final UnboundedLocalCache<K, V> cache;
1011

1012
    EntrySetView(UnboundedLocalCache<K, V> cache) {
1 ✔
1013
      this.cache = requireNonNull(cache);
1 ✔
1014
    }
1 ✔
1015

1016
    @Override
1017
    public boolean isEmpty() {
1018
      return cache.isEmpty();
1 ✔
1019
    }
1020

1021
    @Override
1022
    public int size() {
1023
      return cache.size();
1 ✔
1024
    }
1025

1026
    @Override
1027
    public void clear() {
1028
      cache.clear();
1 ✔
1029
    }
1 ✔
1030

1031
    @Override
1032
    @SuppressWarnings("SuspiciousMethodCalls")
1033
    public boolean contains(@Nullable Object o) {
1034
      if (!(o instanceof Entry<?, ?>)) {
1 ✔
1035
        return false;
1 ✔
1036
      }
1037
      var entry = (Entry<?, ?>) o;
1 ✔
1038
      var key = entry.getKey();
1 ✔
1039
      var value = entry.getValue();
1 ✔
1040
      if ((key == null) || (value == null)) {
1 ✔
1041
        return false;
1 ✔
1042
      }
1043
      V cachedValue = cache.get(key);
1 ✔
1044
      return value.equals(cachedValue);
1 ✔
1045
    }
1046

1047
    @Override
1048
    public boolean containsAll(Collection<?> collection) {
1049
      requireNonNull(collection);
1 ✔
1050
      if (collection != this) {
1 ✔
1051
        for (Object o : collection) {
1 ✔
1052
          if ((o == null) || !contains(o)) {
1 ✔
1053
            return false;
1 ✔
1054
          }
1055
        }
1 ✔
1056
      }
1057
      return true;
1 ✔
1058
    }
1059

1060
    @Override
1061
    public boolean removeAll(Collection<?> collection) {
1062
      requireNonNull(collection);
1 ✔
1063
      @Var boolean modified = false;
1 ✔
1064
      if ((collection instanceof Set<?>) && (collection.size() > size())) {
1 ✔
1065
        for (var entry : this) {
1 ✔
1066
          if (collection.contains(entry)) {
1 ✔
1067
            modified |= remove(entry);
1 ✔
1068
          }
1069
        }
1 ✔
1070
      } else {
1071
        for (var o : collection) {
1 ✔
1072
          modified |= remove(o);
1 ✔
1073
        }
1 ✔
1074
      }
1075
      return modified;
1 ✔
1076
    }
1077

1078
    @Override
1079
    @SuppressWarnings("SuspiciousMethodCalls")
1080
    public boolean remove(@Nullable Object o) {
1081
      if (!(o instanceof Entry<?, ?>)) {
1 ✔
1082
        return false;
1 ✔
1083
      }
1084
      var entry = (Entry<?, ?>) o;
1 ✔
1085
      var key = entry.getKey();
1 ✔
1086
      return (key != null) && cache.remove(key, entry.getValue());
1 ✔
1087
    }
1088

1089
    @Override
1090
    public boolean removeIf(Predicate<? super Entry<K, V>> filter) {
1091
      requireNonNull(filter);
1 ✔
1092
      @Var boolean removed = false;
1 ✔
1093
      for (var entry : cache.data.entrySet()) {
1 ✔
1094
        var key = entry.getKey();
1 ✔
1095
        var value = entry.getValue();
1 ✔
1096
        if (filter.test(Map.entry(key, value))) {
1 ✔
1097
          removed |= cache.remove(key, value);
1 ✔
1098
        }
1099
      }
1 ✔
1100
      return removed;
1 ✔
1101
    }
1102

1103
    @Override
1104
    public boolean retainAll(Collection<?> collection) {
1105
      requireNonNull(collection);
1 ✔
1106
      @Var boolean modified = false;
1 ✔
1107
      for (var entry : this) {
1 ✔
1108
        if (!collection.contains(entry) && remove(entry)) {
1 ✔
1109
          modified = true;
1 ✔
1110
        }
1111
      }
1 ✔
1112
      return modified;
1 ✔
1113
    }
1114

1115
    @Override
1116
    public Iterator<Entry<K, V>> iterator() {
1117
      return new EntryIterator<>(cache);
1 ✔
1118
    }
1119

1120
    @Override
1121
    public Spliterator<Entry<K, V>> spliterator() {
1122
      return new EntrySpliterator<>(cache);
1 ✔
1123
    }
1124
  }
1125

1126
  /** An adapter to safely externalize the entry iterator. */
1127
  static final class EntryIterator<K, V> implements Iterator<Entry<K, V>> {
1128
    final UnboundedLocalCache<K, V> cache;
1129
    final Iterator<Entry<K, V>> iterator;
1130
    @Nullable Entry<K, V> entry;
1131

1132
    EntryIterator(UnboundedLocalCache<K, V> cache) {
1 ✔
1133
      this.iterator = cache.data.entrySet().iterator();
1 ✔
1134
      this.cache = cache;
1 ✔
1135
    }
1 ✔
1136

1137
    @Override
1138
    public boolean hasNext() {
1139
      return iterator.hasNext();
1 ✔
1140
    }
1141

1142
    @Override
1143
    public Entry<K, V> next() {
1144
      entry = iterator.next();
1 ✔
1145
      return new WriteThroughEntry<>(cache, entry.getKey(), entry.getValue());
1 ✔
1146
    }
1147

1148
    @Override
1149
    @SuppressWarnings("ResultOfMethodCallIgnored")
1150
    public void remove() {
1151
      if (entry == null) {
1 ✔
1152
        throw new IllegalStateException();
1 ✔
1153
      }
1154
      cache.remove(entry.getKey());
1 ✔
1155
      entry = null;
1 ✔
1156
    }
1 ✔
1157
  }
1158

1159
  /** An adapter to safely externalize the entry spliterator. */
1160
  static final class EntrySpliterator<K, V> implements Spliterator<Entry<K, V>> {
1161
    final Spliterator<Entry<K, V>> spliterator;
1162
    final UnboundedLocalCache<K, V> cache;
1163

1164
    EntrySpliterator(UnboundedLocalCache<K, V> cache) {
1165
      this(cache, cache.data.entrySet().spliterator());
1 ✔
1166
    }
1 ✔
1167

1168
    EntrySpliterator(UnboundedLocalCache<K, V> cache, Spliterator<Entry<K, V>> spliterator) {
1 ✔
1169
      this.spliterator = requireNonNull(spliterator);
1 ✔
1170
      this.cache = requireNonNull(cache);
1 ✔
1171
    }
1 ✔
1172

1173
    @Override
1174
    public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
1175
      requireNonNull(action);
1 ✔
1176
      spliterator.forEachRemaining(entry -> {
1 ✔
1177
        var e = new WriteThroughEntry<>(cache, entry.getKey(), entry.getValue());
1 ✔
1178
        action.accept(e);
1 ✔
1179
      });
1 ✔
1180
    }
1 ✔
1181

1182
    @Override
1183
    public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
1184
      requireNonNull(action);
1 ✔
1185
      return spliterator.tryAdvance(entry -> {
1 ✔
1186
        var e = new WriteThroughEntry<>(cache, entry.getKey(), entry.getValue());
1 ✔
1187
        action.accept(e);
1 ✔
1188
      });
1 ✔
1189
    }
1190

1191
    @Override
1192
    public @Nullable EntrySpliterator<K, V> trySplit() {
1193
      Spliterator<Entry<K, V>> split = spliterator.trySplit();
1 ✔
1194
      return (split == null) ? null : new EntrySpliterator<>(cache, split);
1 ✔
1195
    }
1196

1197
    @Override
1198
    public long estimateSize() {
1199
      return spliterator.estimateSize();
1 ✔
1200
    }
1201

1202
    @Override
1203
    public int characteristics() {
1204
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
1205
    }
1206
  }
1207

1208
  /* --------------- Manual Cache --------------- */
1209

1210
  static class UnboundedLocalManualCache<K, V> implements LocalManualCache<K, V>, Serializable {
1211
    private static final long serialVersionUID = 1;
1212

1213
    final UnboundedLocalCache<K, V> cache;
1214
    @Nullable Policy<K, V> policy;
1215

1216
    UnboundedLocalManualCache(Caffeine<K, V> builder) {
1 ✔
1217
      cache = new UnboundedLocalCache<>(builder, /* isAsync= */ false);
1 ✔
1218
    }
1 ✔
1219

1220
    @Override
1221
    public final UnboundedLocalCache<K, V> cache() {
1222
      return cache;
1 ✔
1223
    }
1224

1225
    @Override
1226
    public final Policy<K, V> policy() {
1227
      @Var var p = policy;
1 ✔
1228
      if (p == null) {
1 ✔
1229
        Function<@Nullable V, @Nullable V> identity = v -> v;
1 ✔
1230
        p = new UnboundedPolicy<>(cache, identity);
1 ✔
1231
        policy = p;
1 ✔
1232
      }
1233
      return p;
1 ✔
1234
    }
1235

1236
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1237
      throw new InvalidObjectException("Proxy required");
1 ✔
1238
    }
1239

1240
    Object writeReplace() {
1241
      var proxy = new SerializationProxy<K, V>();
1 ✔
1242
      proxy.isRecordingStats = cache.isRecordingStats;
1 ✔
1243
      proxy.removalListener = cache.removalListener;
1 ✔
1244
      return proxy;
1 ✔
1245
    }
1246
  }
1247

1248
  /** An eviction policy that supports no bounding. */
1249
  static final class UnboundedPolicy<K, V> implements Policy<K, V> {
1250
    final Function<@Nullable V, @Nullable V> transformer;
1251
    final UnboundedLocalCache<K, V> cache;
1252

1253
    UnboundedPolicy(UnboundedLocalCache<K, V> cache,
1254
        Function<@Nullable V, @Nullable V> transformer) {
1 ✔
1255
      this.transformer = transformer;
1 ✔
1256
      this.cache = cache;
1 ✔
1257
    }
1 ✔
1258
    @Override public boolean isRecordingStats() {
1259
      return cache.isRecordingStats;
1 ✔
1260
    }
1261
    @Override public @Nullable V getIfPresentQuietly(K key) {
1262
      return transformer.apply(cache.data.get(key));
1 ✔
1263
    }
1264
    @Override public @Nullable CacheEntry<K, V> getEntryIfPresentQuietly(K key) {
1265
      V value = transformer.apply(cache.data.get(key));
1 ✔
1266
      return (value == null) ? null : SnapshotEntry.forEntry(key, value);
1 ✔
1267
    }
1268
    @SuppressWarnings("Java9CollectionFactory")
1269
    @Override public Map<K, CompletableFuture<V>> refreshes() {
1270
      var refreshes = cache.refreshes;
1 ✔
1271
      if ((refreshes == null) || refreshes.isEmpty()) {
1 ✔
1272
        @SuppressWarnings({"ImmutableMapOf", "RedundantUnmodifiable"})
1273
        Map<K, CompletableFuture<V>> emptyMap = Collections.unmodifiableMap(Collections.emptyMap());
1 ✔
1274
        return emptyMap;
1 ✔
1275
      }
1276
      @SuppressWarnings("unchecked")
1277
      var castedRefreshes = (Map<K, CompletableFuture<V>>) (Object) refreshes;
1 ✔
1278
      var inFlight = new HashMap<>(castedRefreshes);
1 ✔
1279
      inFlight.values().removeIf(LocalLoadingCache.PendingRefresh.class::isInstance);
1 ✔
1280
      return Collections.unmodifiableMap(inFlight);
1 ✔
1281
    }
1282
    @Override public Optional<Eviction<K, V>> eviction() {
1283
      return Optional.empty();
1 ✔
1284
    }
1285
    @Override public Optional<FixedExpiration<K, V>> expireAfterAccess() {
1286
      return Optional.empty();
1 ✔
1287
    }
1288
    @Override public Optional<FixedExpiration<K, V>> expireAfterWrite() {
1289
      return Optional.empty();
1 ✔
1290
    }
1291
    @Override public Optional<VarExpiration<K, V>> expireVariably() {
1292
      return Optional.empty();
1 ✔
1293
    }
1294
    @Override public Optional<FixedRefresh<K, V>> refreshAfterWrite() {
1295
      return Optional.empty();
1 ✔
1296
    }
1297
  }
1298

1299
  /* --------------- Loading Cache --------------- */
1300

1301
  static final class UnboundedLocalLoadingCache<K, V> extends UnboundedLocalManualCache<K, V>
1302
      implements LocalLoadingCache<K, V> {
1303
    private static final long serialVersionUID = 1;
1304

1305
    final Function<K, @Nullable V> mappingFunction;
1306
    final CacheLoader<? super K, V> cacheLoader;
1307
    final @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction;
1308

1309
    UnboundedLocalLoadingCache(Caffeine<K, V> builder, CacheLoader<? super K, V> cacheLoader) {
1310
      super(builder);
1 ✔
1311
      this.cacheLoader = cacheLoader;
1 ✔
1312
      this.mappingFunction = newMappingFunction(cacheLoader);
1 ✔
1313
      this.bulkMappingFunction = newBulkMappingFunction(cacheLoader);
1 ✔
1314
    }
1 ✔
1315

1316
    @Override
1317
    public AsyncCacheLoader<? super K, V> cacheLoader() {
1318
      return cacheLoader;
1 ✔
1319
    }
1320

1321
    @Override
1322
    public Function<K, @Nullable V> mappingFunction() {
1323
      return mappingFunction;
1 ✔
1324
    }
1325

1326
    @Override
1327
    public @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction() {
1328
      return bulkMappingFunction;
1 ✔
1329
    }
1330

1331
    @Override
1332
    Object writeReplace() {
1333
      @SuppressWarnings("unchecked")
1334
      var proxy = (SerializationProxy<K, V>) super.writeReplace();
1 ✔
1335
      proxy.cacheLoader = cacheLoader;
1 ✔
1336
      return proxy;
1 ✔
1337
    }
1338

1339
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1340
      throw new InvalidObjectException("Proxy required");
1 ✔
1341
    }
1342
  }
1343

1344
  /* --------------- Async Cache --------------- */
1345

1346
  static final class UnboundedLocalAsyncCache<K, V> implements LocalAsyncCache<K, V>, Serializable {
1347
    private static final long serialVersionUID = 1;
1348

1349
    final UnboundedLocalCache<K, CompletableFuture<V>> cache;
1350

1351
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
1352
    @Nullable CacheView<K, V> cacheView;
1353
    @Nullable Policy<K, V> policy;
1354

1355
    @SuppressWarnings("unchecked")
1356
    UnboundedLocalAsyncCache(Caffeine<K, V> builder) {
1 ✔
1357
      cache = new UnboundedLocalCache<>(
1 ✔
1358
          (Caffeine<K, CompletableFuture<V>>) builder, /* isAsync= */ true);
1359
    }
1 ✔
1360

1361
    @Override
1362
    public UnboundedLocalCache<K, CompletableFuture<V>> cache() {
1363
      return cache;
1 ✔
1364
    }
1365

1366
    @Override
1367
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
1368
      var mv = mapView;
1 ✔
1369
      return (mv == null) ? (mapView = new AsyncAsMapView<>(this)) : mv;
1 ✔
1370
    }
1371

1372
    @Override
1373
    public Cache<K, V> synchronous() {
1374
      var cv = cacheView;
1 ✔
1375
      return (cv == null) ? (cacheView = new CacheView<>(this)) : cv;
1 ✔
1376
    }
1377

1378
    @Override
1379
    public Policy<K, V> policy() {
1380
      @SuppressWarnings("unchecked")
1381
      var castCache = (UnboundedLocalCache<K, V>) cache;
1 ✔
1382
      Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1 ✔
1383
      @SuppressWarnings("unchecked")
1384
      var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1 ✔
1385
      var p = policy;
1 ✔
1386
      return (p == null)
1 ✔
1387
          ? (policy = new UnboundedPolicy<>(castCache, castTransformer))
1 ✔
1388
          : p;
1 ✔
1389
    }
1390

1391
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1392
      throw new InvalidObjectException("Proxy required");
1 ✔
1393
    }
1394

1395
    Object writeReplace() {
1396
      var proxy = new SerializationProxy<K, V>();
1 ✔
1397
      proxy.isRecordingStats = cache.isRecordingStats;
1 ✔
1398
      proxy.removalListener = cache.removalListener;
1 ✔
1399
      proxy.async = true;
1 ✔
1400
      return proxy;
1 ✔
1401
    }
1402
  }
1403

1404
  /* --------------- Async Loading Cache --------------- */
1405

1406
  static final class UnboundedLocalAsyncLoadingCache<K, V>
1407
      extends LocalAsyncLoadingCache<K, V> implements Serializable {
1408
    private static final long serialVersionUID = 1;
1409

1410
    final UnboundedLocalCache<K, CompletableFuture<V>> cache;
1411

1412
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
1413
    @Nullable Policy<K, V> policy;
1414

1415
    @SuppressWarnings("unchecked")
1416
    UnboundedLocalAsyncLoadingCache(Caffeine<K, V> builder, AsyncCacheLoader<? super K, V> loader) {
1417
      super(loader);
1 ✔
1418
      cache = new UnboundedLocalCache<>(
1 ✔
1419
          (Caffeine<K, CompletableFuture<V>>) builder, /* isAsync= */ true);
1420
    }
1 ✔
1421

1422
    @Override
1423
    public LocalCache<K, CompletableFuture<V>> cache() {
1424
      return cache;
1 ✔
1425
    }
1426

1427
    @Override
1428
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
1429
      var mv = mapView;
1 ✔
1430
      return (mv == null) ? (mapView = new AsyncAsMapView<>(this)) : mv;
1 ✔
1431
    }
1432

1433
    @Override
1434
    public Policy<K, V> policy() {
1435
      @SuppressWarnings("unchecked")
1436
      var castCache = (UnboundedLocalCache<K, V>) cache;
1 ✔
1437
      Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1 ✔
1438
      @SuppressWarnings("unchecked")
1439
      var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1 ✔
1440
      var p = policy;
1 ✔
1441
      return (p == null)
1 ✔
1442
          ? (policy = new UnboundedPolicy<>(castCache, castTransformer))
1 ✔
1443
          : p;
1 ✔
1444
    }
1445

1446
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
1447
      throw new InvalidObjectException("Proxy required");
1 ✔
1448
    }
1449

1450
    Object writeReplace() {
1451
      var proxy = new SerializationProxy<K, V>();
1 ✔
1452
      proxy.isRecordingStats = cache.isRecordingStats();
1 ✔
1453
      proxy.removalListener = cache.removalListener;
1 ✔
1454
      proxy.cacheLoader = cacheLoader;
1 ✔
1455
      proxy.async = true;
1 ✔
1456
      return proxy;
1 ✔
1457
    }
1458
  }
1459
}
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