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

ben-manes / caffeine / #5588

05 Jul 2026 04:11AM UTC coverage: 99.772% (-0.1%) from 99.904%
#5588

push

github

ben-manes
Make the async asMap() view equals reflexive

AsyncAsMapView.equals delegated straight to cache().equals(o), so a
self-compare skipped the o == this short-circuit its three sibling
views have. cache().equals then returns false whenever it iterates
an expired-but-unreaped (or collected) entry, so view.equals(view)
could break Object.equals reflexivity. Prepend the identity check.

4061 of 4086 branches covered (99.39%)

1 of 1 new or added line in 1 file covered. (100.0%)

11 existing lines in 4 files now uncovered.

8314 of 8333 relevant lines covered (99.77%)

1.0 hits per line

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

99.79
/caffeine/src/main/java/com/github/benmanes/caffeine/cache/BoundedLocalCache.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.Async.ASYNC_EXPIRY;
19
import static com.github.benmanes.caffeine.cache.Caffeine.calculateHashMapCapacity;
20
import static com.github.benmanes.caffeine.cache.Caffeine.ceilingPowerOfTwo;
21
import static com.github.benmanes.caffeine.cache.Caffeine.requireArgument;
22
import static com.github.benmanes.caffeine.cache.Caffeine.toNanosSaturated;
23
import static com.github.benmanes.caffeine.cache.LocalLoadingCache.newBulkMappingFunction;
24
import static com.github.benmanes.caffeine.cache.LocalLoadingCache.newMappingFunction;
25
import static com.github.benmanes.caffeine.cache.Node.PROBATION;
26
import static com.github.benmanes.caffeine.cache.Node.PROTECTED;
27
import static com.github.benmanes.caffeine.cache.Node.WINDOW;
28
import static java.lang.invoke.ConstantBootstraps.fieldVarHandle;
29
import static java.util.Locale.US;
30
import static java.util.Objects.requireNonNull;
31
import static java.util.Spliterator.DISTINCT;
32
import static java.util.Spliterator.IMMUTABLE;
33
import static java.util.Spliterator.NONNULL;
34
import static java.util.Spliterator.ORDERED;
35

36
import java.io.InvalidObjectException;
37
import java.io.ObjectInputStream;
38
import java.io.Serializable;
39
import java.lang.System.Logger;
40
import java.lang.System.Logger.Level;
41
import java.lang.invoke.MethodHandles;
42
import java.lang.invoke.VarHandle;
43
import java.lang.ref.Reference;
44
import java.lang.ref.ReferenceQueue;
45
import java.lang.ref.WeakReference;
46
import java.time.Duration;
47
import java.util.AbstractCollection;
48
import java.util.AbstractSet;
49
import java.util.ArrayDeque;
50
import java.util.Collection;
51
import java.util.Collections;
52
import java.util.Comparator;
53
import java.util.Deque;
54
import java.util.HashMap;
55
import java.util.IdentityHashMap;
56
import java.util.Iterator;
57
import java.util.LinkedHashMap;
58
import java.util.Map;
59
import java.util.NoSuchElementException;
60
import java.util.Objects;
61
import java.util.Optional;
62
import java.util.OptionalInt;
63
import java.util.OptionalLong;
64
import java.util.Set;
65
import java.util.Spliterator;
66
import java.util.Spliterators;
67
import java.util.concurrent.CancellationException;
68
import java.util.concurrent.CompletableFuture;
69
import java.util.concurrent.CompletionException;
70
import java.util.concurrent.ConcurrentHashMap;
71
import java.util.concurrent.ConcurrentMap;
72
import java.util.concurrent.Executor;
73
import java.util.concurrent.ForkJoinPool;
74
import java.util.concurrent.ForkJoinTask;
75
import java.util.concurrent.ThreadLocalRandom;
76
import java.util.concurrent.TimeUnit;
77
import java.util.concurrent.TimeoutException;
78
import java.util.concurrent.locks.ReentrantLock;
79
import java.util.function.BiConsumer;
80
import java.util.function.BiFunction;
81
import java.util.function.Consumer;
82
import java.util.function.Function;
83
import java.util.function.Predicate;
84
import java.util.stream.Stream;
85
import java.util.stream.StreamSupport;
86

87
import org.jspecify.annotations.NonNull;
88
import org.jspecify.annotations.Nullable;
89

90
import com.github.benmanes.caffeine.cache.Async.AsyncExpiry;
91
import com.github.benmanes.caffeine.cache.LinkedDeque.PeekingIterator;
92
import com.github.benmanes.caffeine.cache.Policy.CacheEntry;
93
import com.github.benmanes.caffeine.cache.References.InternalReference;
94
import com.github.benmanes.caffeine.cache.stats.StatsCounter;
95
import com.google.errorprone.annotations.CanIgnoreReturnValue;
96
import com.google.errorprone.annotations.Var;
97
import com.google.errorprone.annotations.concurrent.GuardedBy;
98

99
/**
100
 * An in-memory cache implementation that supports full concurrency of retrievals, a high expected
101
 * concurrency for updates, and multiple ways to bound the cache.
102
 * <p>
103
 * This class is abstract and code generated subclasses provide the complete implementation for a
104
 * particular configuration. This is to ensure that only the fields and execution paths necessary
105
 * for a given configuration are used.
106
 *
107
 * @author ben.manes@gmail.com (Ben Manes)
108
 * @param <K> the type of keys maintained by this cache
109
 * @param <V> the type of mapped values
110
 */
111
@SuppressWarnings({"RedundantSuppression", "ResultOfMethodCallIgnored", "serial", "unused"})
112
abstract class BoundedLocalCache<K, V> extends BLCHeader.DrainStatusRef
113
    implements LocalCache<K, V> {
114

115
  /*
116
   * This class performs a best-effort bounding of a ConcurrentHashMap using a page-replacement
117
   * algorithm to determine which entries to evict when the capacity is exceeded.
118
   *
119
   * Concurrency:
120
   * ------------
121
   * The page replacement algorithms are kept eventually consistent with the map. An update to the
122
   * map and recording of reads may not be immediately reflected in the policy's data structures.
123
   * These structures are guarded by a lock, and operations are applied in batches to avoid lock
124
   * contention. The penalty of applying the batches is spread across threads, so that the amortized
125
   * cost is slightly higher than performing just the ConcurrentHashMap operation [1].
126
   *
127
   * A memento of the reads and writes that were performed on the map is recorded in buffers. These
128
   * buffers are drained at the first opportunity after a write or when a read buffer is full. The
129
   * reads are offered to a buffer that will reject additions if contended on or if it is full. Due
130
   * to the concurrent nature of the read and write operations, a strict policy ordering is not
131
   * possible, but it may be observably strict when single-threaded. The buffers are drained
132
   * asynchronously to minimize the request latency and uses a state machine to determine when to
133
   * schedule this work on an executor.
134
   *
135
   * Due to a lack of a strict ordering guarantee, a task can be executed out-of-order, such as a
136
   * removal followed by its addition. The state of the entry is encoded using the key field to
137
   * avoid additional memory usage. An entry is "alive" if it is in both the hash table and the page
138
   * replacement policy. It is "retired" if it is not in the hash table and is pending removal from
139
   * the page replacement policy. Finally, an entry transitions to the "dead" state when it is
140
   * neither in the hash table nor the page replacement policy. Both the retired and dead states are
141
   * represented by a sentinel key that should not be used for map operations.
142
   *
143
   * Eviction:
144
   * ---------
145
   * Maximum size is implemented using the Window TinyLfu policy [2] due to its high hit rate, O(1)
146
   * time complexity, and small footprint. A new entry starts in the admission window and remains
147
   * there as long as it has high temporal locality (recency). Eventually an entry will slip from
148
   * the window into the main space. If the main space is already full, then a historic frequency
149
   * filter determines whether to evict the newly admitted entry or the victim entry chosen by the
150
   * eviction policy. This process ensures that the entries in the window were very recently used,
151
   * while entries in the main space are accessed very frequently and remain moderately recent. The
152
   * windowing allows the policy to have a high hit rate when entries exhibit a bursty access
153
   * pattern, while the filter ensures that popular items are retained. The admission window uses
154
   * LRU and the main space uses Segmented LRU.
155
   *
156
   * The optimal size of the window vs. main spaces is workload dependent [3]. A large admission
157
   * window is favored by recency-biased workloads, while a small one favors frequency-biased
158
   * workloads. When the window is too small, then recent arrivals are prematurely evicted, but when
159
   * it is too large, then they pollute the cache and force the eviction of more popular entries.
160
   * The optimal configuration is dynamically determined by using hill climbing to walk the hit rate
161
   * curve. This is achieved by sampling the hit rate and adjusting the window size in the direction
162
   * that is improving (making positive or negative steps). At each interval, the step size is
163
   * decreased until the hit rate climber converges at the optimal setting. For small caches the
164
   * sample period grows as its step decays to avoid getting stuck at a poor initial configuration.
165
   * The process is restarted when the hit rate changes over a threshold, indicating that the
166
   * workload altered, and a new setting may be required.
167
   *
168
   * The historic usage is retained in a compact popularity sketch, which uses hashing to
169
   * probabilistically estimate an item's frequency. This exposes a flaw where an adversary could
170
   * use hash flooding [4] to artificially raise the frequency of the main space's victim and cause
171
   * all candidates to be rejected. In the worst case, by exploiting hash collisions, an attacker
172
   * could cause the cache to never hit and hold only worthless items, resulting in a
173
   * denial-of-service attack against the underlying resource. This is mitigated by introducing
174
   * jitter, allowing candidates that are at least moderately popular to have a small, random chance
175
   * of being admitted. This causes the victim to be evicted, but in a way that marginally impacts
176
   * the hit rate.
177
   *
178
   * Expiration:
179
   * -----------
180
   * Expiration is implemented in O(1) time complexity. The time-to-idle policy uses an access-order
181
   * queue, the time-to-live policy uses a write-order queue, and variable expiration uses a
182
   * hierarchical timer wheel [5]. The queuing policies allow for peeking at the oldest entry to
183
   * determine if it has expired. If it has not, then the younger entries must not have expired
184
   * either. If a maximum size is set, then expiration will share the queues, minimizing the
185
   * per-entry footprint. The timer wheel based policy uses hashing and cascading in a manner that
186
   * amortizes the penalty of sorting to achieve a similar algorithmic cost.
187
   *
188
   * The expiration updates are applied in a best effort fashion. The reordering of variable or
189
   * access-order expiration may be discarded by the read buffer if it is full or contended.
190
   * Similarly, recording the touch for expiration to extend its lifetime may be ignored for an
191
   * entry if the last update was within a short time window. This is done to avoid overwhelming the
192
   * write buffer and to avoid false sharing on reads due to modifying the access time. The
193
   * expiration scan compensates by moving a stale-positioned head to the back of the queue when its
194
   * timestamp is fresher than the tail, so subsequent passes can resume from the next-oldest entry.
195
   *
196
   * [1] BP-Wrapper: A Framework Making Any Replacement Algorithms (Almost) Lock Contention Free
197
   * https://web.njit.edu/~dingxn/papers/BP-Wrapper.pdf
198
   * [2] TinyLFU: A Highly Efficient Cache Admission Policy
199
   * https://dl.acm.org/citation.cfm?id=3149371
200
   * [3] Adaptive Software Cache Management
201
   * https://dl.acm.org/citation.cfm?id=3274816
202
   * [4] Denial of Service via Algorithmic Complexity Attack
203
   * https://www.usenix.org/legacy/events/sec03/tech/full_papers/crosby/crosby.pdf
204
   * [5] Hashed and Hierarchical Timing Wheels
205
   * http://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-wheels.pdf
206
   */
207

208
  static final Logger logger = System.getLogger(BoundedLocalCache.class.getName());
1✔
209

210
  /** The number of CPUs */
211
  static final int NCPU = Runtime.getRuntime().availableProcessors();
1✔
212
  /** The initial capacity of the write buffer. */
213
  static final int WRITE_BUFFER_MIN = 4;
214
  /** The maximum capacity of the write buffer. */
215
  static final int WRITE_BUFFER_MAX = 128 * ceilingPowerOfTwo(NCPU);
1✔
216
  /** The maximum weighted capacity of the map. */
217
  static final long MAXIMUM_CAPACITY = Long.MAX_VALUE - Integer.MAX_VALUE;
218
  /** The initial percent of the maximum weighted capacity dedicated to the main space. */
219
  static final double PERCENT_MAIN = 0.99d;
220
  /** The percent of the maximum weighted capacity dedicated to the main's protected space. */
221
  static final double PERCENT_MAIN_PROTECTED = 0.80d;
222
  /** The difference in hit rates that restarts the climber. */
223
  static final double HILL_CLIMBER_RESTART_THRESHOLD = 0.05d;
224
  /** The percent of the total size to adapt the window by. */
225
  static final double HILL_CLIMBER_STEP_PERCENT = 0.0625d;
226
  /** The rate to decrease the step size to adapt by. */
227
  static final double HILL_CLIMBER_STEP_DECAY_RATE = 0.98d;
228
  /** Lower bound on the initial step size so that small caches have an opportunity to adapt. */
229
  static final double HILL_CLIMBER_MIN_INITIAL_STEP = 2.0d;
230
  /** The threshold below which the climber's sample period grows as its step size decays. */
231
  static final long SMALL_CACHE_THRESHOLD = 512L;
232
  /** Maximum factor by which the climber's sample period may grow. */
233
  static final double SMALL_CACHE_SAMPLE_RATIO_CAP = 4.0d;
234
  /** The step decay rate for small caches, slower to keep the step large enough for restarts. */
235
  static final double SMALL_CACHE_STEP_DECAY_RATE = 0.995d;
236
  /** The minimum popularity for allowing randomized admission. */
237
  static final int ADMIT_HASHDOS_THRESHOLD = 6;
238
  /** The maximum number of entries that can be transferred between queues. */
239
  static final int QUEUE_TRANSFER_THRESHOLD = 1_000;
240
  /** The maximum number of entries that can be expired per maintenance cycle. */
241
  static final int EXPIRATION_THRESHOLD = 1_000;
242
  /** The maximum time window between touches for expiration updates. */
243
  static final long EXPIRE_TOLERANCE = TimeUnit.SECONDS.toNanos(1);
1✔
244
  /** The maximum duration before an entry expires. */
245
  static final long MAXIMUM_EXPIRY = (Long.MAX_VALUE >> 1); // 150 years
246
  /** The duration to wait on the eviction lock before warning of a possible misuse. */
247
  static final long WARN_AFTER_LOCK_WAIT_NANOS = TimeUnit.SECONDS.toNanos(30);
1✔
248
  /** The number of retries before computing to validate the entry's integrity; pow2 modulus. */
249
  static final int MAX_PUT_SPIN_WAIT_ATTEMPTS = 1024 - 1;
250
  /** The handle for the in-flight refresh operations. */
251
  static final VarHandle REFRESHES = fieldVarHandle(MethodHandles.lookup(),
1✔
252
      "refreshes", VarHandle.class, BoundedLocalCache.class, ConcurrentMap.class);
253

254
  final @Nullable RemovalListener<K, V> evictionListener;
255
  final @Nullable AsyncCacheLoader<K, V> cacheLoader;
256

257
  final MpscGrowableArrayQueue<Runnable> writeBuffer;
258
  final ConcurrentHashMap<Object, Node<K, V>> data;
259
  final PerformCleanupTask drainBuffersTask;
260
  final Consumer<Node<K, V>> accessPolicy;
261
  final Buffer<Node<K, V>> readBuffer;
262
  final NodeFactory<K, V> nodeFactory;
263
  final ReentrantLock evictionLock;
264
  final Weigher<K, V> weigher;
265
  final Executor executor;
266

267
  final boolean isWeighted;
268
  final boolean isAsync;
269

270
  @Nullable Set<K> keySet;
271
  @Nullable Collection<V> values;
272
  @Nullable Set<Entry<K, V>> entrySet;
273
  volatile @Nullable ConcurrentMap<Object, CompletableFuture<?>> refreshes;
274

275
  /** Creates an instance based on the builder's configuration. */
276
  @SuppressWarnings("GuardedBy")
277
  protected BoundedLocalCache(Caffeine<K, V> builder,
278
      @Nullable AsyncCacheLoader<K, V> cacheLoader, boolean isAsync) {
1✔
279
    this.isAsync = isAsync;
1✔
280
    this.cacheLoader = cacheLoader;
1✔
281
    executor = builder.getExecutor();
1✔
282
    isWeighted = builder.isWeighted();
1✔
283
    evictionLock = new ReentrantLock();
1✔
284
    weigher = builder.getWeigher(isAsync);
1✔
285
    drainBuffersTask = new PerformCleanupTask(this);
1✔
286
    nodeFactory = NodeFactory.newFactory(builder, isAsync);
1✔
287
    evictionListener = builder.getEvictionListener(isAsync);
1✔
288
    data = new ConcurrentHashMap<>(builder.getInitialCapacity());
1✔
289
    readBuffer = evicts() || collectKeys() || collectValues() || expiresAfterAccess()
1✔
290
        ? new BoundedBuffer<>()
1✔
291
        : Buffer.disabled();
1✔
292
    accessPolicy = (evicts() || expiresAfterAccess()) ? this::onAccess : e -> {};
1✔
293
    writeBuffer = new MpscGrowableArrayQueue<>(WRITE_BUFFER_MIN, WRITE_BUFFER_MAX);
1✔
294

295
    if (evicts()) {
1✔
296
      setMaximumSize(builder.getMaximum());
1✔
297
    }
298
  }
1✔
299

300
  /** Ensures that the node is alive during the map operation. */
301
  void requireIsAlive(Object key, Node<?, ?> node) {
302
    if (!node.isAlive()) {
1✔
303
      throw new IllegalStateException(brokenEqualityMessage(key, node));
1✔
304
    }
305
  }
1✔
306

307
  /** Logs if the node cannot be found in the map but is still alive. */
308
  void logIfAlive(Node<?, ?> node) {
309
    if (node.isAlive()) {
1✔
310
      String message = brokenEqualityMessage(node.getKeyReference(), node);
1✔
311
      logger.log(Level.ERROR, message, new IllegalStateException());
1✔
312
    }
313
  }
1✔
314

315
  /** Returns the formatted broken equality error message. */
316
  String brokenEqualityMessage(Object key, Node<?, ?> node) {
317
    return String.format(US, "An invalid state was detected, occurring when the key's equals or "
1✔
318
        + "hashCode was modified while residing in the cache. This violation of the Map "
319
        + "contract can lead to non-deterministic behavior (key: %s, key type: %s, "
320
        + "node type: %s, cache type: %s).", key, key.getClass().getName(),
1✔
321
        node.getClass().getSimpleName(), getClass().getSimpleName());
1✔
322
  }
323

324
  /** Returns the exception as unchecked, wrapping checked exceptions in a CompletionException. */
325
  static RuntimeException toUncheckedException(Throwable t) {
326
    if (t instanceof Error) {
1✔
327
      throw (Error) t;
1✔
328
    }
329
    return (t instanceof RuntimeException) ? (RuntimeException) t : new CompletionException(t);
1✔
330
  }
331

332
  /* --------------- Shared --------------- */
333

334
  @Override
335
  public boolean isAsync() {
336
    return isAsync;
1✔
337
  }
338

339
  /** Returns if the node's value is currently being computed asynchronously. */
340
  final boolean isComputingAsync(@Nullable V value) {
341
    return isAsync && !Async.isReady((CompletableFuture<?>) value);
1✔
342
  }
343

344
  @GuardedBy("evictionLock")
345
  protected AccessOrderDeque<Node<K, V>> accessOrderWindowDeque() {
346
    throw new UnsupportedOperationException();
1✔
347
  }
348

349
  @GuardedBy("evictionLock")
350
  protected AccessOrderDeque<Node<K, V>> accessOrderProbationDeque() {
351
    throw new UnsupportedOperationException();
1✔
352
  }
353

354
  @GuardedBy("evictionLock")
355
  protected AccessOrderDeque<Node<K, V>> accessOrderProtectedDeque() {
356
    throw new UnsupportedOperationException();
1✔
357
  }
358

359
  @GuardedBy("evictionLock")
360
  protected WriteOrderDeque<Node<K, V>> writeOrderDeque() {
361
    throw new UnsupportedOperationException();
1✔
362
  }
363

364
  @Override
365
  public final Executor executor() {
366
    return executor;
1✔
367
  }
368

369
  @Override
370
  public ConcurrentMap<Object, CompletableFuture<?>> refreshes() {
371
    @Var var pending = refreshes;
1✔
372
    if (pending == null) {
1✔
373
      pending = new ConcurrentHashMap<>();
1✔
374
      if (!REFRESHES.compareAndSet(this, null, pending)) {
1✔
375
        pending = requireNonNull(refreshes);
1✔
376
      }
377
    }
378
    return pending;
1✔
379
  }
380

381
  /** Invalidate the in-flight refresh. */
382
  @SuppressWarnings("RedundantCollectionOperation")
383
  void discardRefresh(Object keyReference) {
384
    var pending = refreshes;
1✔
385
    if ((pending != null) && pending.containsKey(keyReference)) {
1✔
386
      pending.remove(keyReference);
1✔
387
    }
388
  }
1✔
389

390
  @Override
391
  public Object referenceKey(K key) {
392
    return nodeFactory.newLookupKey(key);
1✔
393
  }
394

395
  @Override
396
  public boolean isPendingEviction(K key) {
397
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
398
    if (node == null) {
1✔
399
      return false;
1✔
400
    }
401
    V value = node.getValue();
1✔
402
    return (value == null) || hasExpired(node, expirationTicker().read(), value);
1✔
403
  }
404

405
  /* --------------- Stats Support --------------- */
406

407
  @Override
408
  public boolean isRecordingStats() {
409
    return false;
1✔
410
  }
411

412
  @Override
413
  public StatsCounter statsCounter() {
414
    return StatsCounter.disabledStatsCounter();
1✔
415
  }
416

417
  @Override
418
  public Ticker statsTicker() {
419
    return Ticker.disabledTicker();
1✔
420
  }
421

422
  /* --------------- Removal Listener Support --------------- */
423

424
  @Override
425
  public @Nullable RemovalListener<K, V> removalListener() {
426
    return null;
1✔
427
  }
428

429
  @Override
430
  public void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause) {
431
    var removalListener = removalListener();
1✔
432
    if (removalListener == null) {
1✔
433
      return;
1✔
434
    }
435
    Runnable task = () -> {
1✔
436
      try {
437
        removalListener.onRemoval(key, value, cause);
1✔
438
      } catch (Throwable t) {
1✔
439
        logger.log(Level.WARNING, "Exception thrown by removal listener", t);
1✔
440
      }
1✔
441
    };
1✔
442
    try {
443
      executor.execute(task);
1✔
444
    } catch (Throwable t) {
1✔
445
      logger.log(Level.ERROR, "Exception thrown when submitting removal listener", t);
1✔
446
      task.run();
1✔
447
    }
1✔
448
  }
1✔
449

450
  /* --------------- Eviction Listener Support --------------- */
451

452
  void notifyEviction(@Nullable K key, @Nullable V value, RemovalCause cause) {
453
    if (evictionListener == null) {
1✔
454
      return;
1✔
455
    }
456
    try {
457
      evictionListener.onRemoval(key, value, cause);
1✔
458
    } catch (Throwable t) {
1✔
459
      logger.log(Level.WARNING, "Exception thrown by eviction listener", t);
1✔
460
    }
1✔
461
  }
1✔
462

463
  /* --------------- Reference Support --------------- */
464

465
  @Override
466
  public boolean collectKeys() {
467
    return false;
1✔
468
  }
469

470
  /** Returns if the values are weak or soft reference garbage collected. */
471
  protected boolean collectValues() {
472
    return false;
1✔
473
  }
474

475
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
476
  protected ReferenceQueue<K> keyReferenceQueue() {
477
    return null;
1✔
478
  }
479

480
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
481
  protected ReferenceQueue<V> valueReferenceQueue() {
482
    return null;
1✔
483
  }
484

485
  /* --------------- Expiration Support --------------- */
486

487
  /** Returns the {@link Pacer} used to schedule the maintenance task. */
488
  protected @Nullable Pacer pacer() {
489
    return null;
1✔
490
  }
491

492
  /** Returns if the cache expires entries after a variable time threshold. */
493
  protected boolean expiresVariable() {
494
    return false;
1✔
495
  }
496

497
  /** Returns if the cache expires entries after an access time threshold. */
498
  protected boolean expiresAfterAccess() {
499
    return false;
1✔
500
  }
501

502
  /** Returns how long after the last access to an entry the map will retain that entry. */
503
  protected long expiresAfterAccessNanos() {
504
    throw new UnsupportedOperationException();
1✔
505
  }
506

507
  protected void setExpiresAfterAccessNanos(long expireAfterAccessNanos) {
508
    throw new UnsupportedOperationException();
1✔
509
  }
510

511
  /** Returns if the cache expires entries after a write time threshold. */
512
  protected boolean expiresAfterWrite() {
513
    return false;
1✔
514
  }
515

516
  /** Returns how long after the last write to an entry the map will retain that entry. */
517
  protected long expiresAfterWriteNanos() {
518
    throw new UnsupportedOperationException();
1✔
519
  }
520

521
  protected void setExpiresAfterWriteNanos(long expireAfterWriteNanos) {
522
    throw new UnsupportedOperationException();
1✔
523
  }
524

525
  /** Returns if the cache refreshes entries after a write time threshold. */
526
  protected boolean refreshAfterWrite() {
527
    return false;
1✔
528
  }
529

530
  /** Returns how long after the last write an entry becomes a candidate for refresh. */
531
  protected long refreshAfterWriteNanos() {
532
    throw new UnsupportedOperationException();
1✔
533
  }
534

535
  protected void setRefreshAfterWriteNanos(long refreshAfterWriteNanos) {
536
    throw new UnsupportedOperationException();
1✔
537
  }
538

539
  @Override
540
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
541
  public Expiry<K, V> expiry() {
542
    return null;
1✔
543
  }
544

545
  /** Returns the {@link Ticker} used by this cache for expiration. */
546
  public Ticker expirationTicker() {
547
    return Ticker.disabledTicker();
1✔
548
  }
549

550
  protected TimerWheel<K, V> timerWheel() {
551
    throw new UnsupportedOperationException();
1✔
552
  }
553

554
  /* --------------- Eviction Support --------------- */
555

556
  /** Returns if the cache evicts entries due to a maximum size or weight threshold. */
557
  protected boolean evicts() {
558
    return false;
1✔
559
  }
560

561
  /** Returns if entries may be assigned different weights. */
562
  protected boolean isWeighted() {
563
    return (weigher != Weigher.singletonWeigher());
1✔
564
  }
565

566
  protected FrequencySketch frequencySketch() {
567
    throw new UnsupportedOperationException();
1✔
568
  }
569

570
  /** Returns if an access to an entry can skip notifying the eviction policy. */
571
  protected boolean fastpath() {
572
    return false;
1✔
573
  }
574

575
  /** Returns the maximum weighted size. */
576
  protected long maximum() {
577
    throw new UnsupportedOperationException();
1✔
578
  }
579

580
  /** Returns the maximum weighted size. */
581
  protected long maximumAcquire() {
582
    throw new UnsupportedOperationException();
1✔
583
  }
584

585
  /** Returns the maximum weighted size of the window space. */
586
  protected long windowMaximum() {
587
    throw new UnsupportedOperationException();
1✔
588
  }
589

590
  /** Returns the maximum weighted size of the main's protected space. */
591
  protected long mainProtectedMaximum() {
592
    throw new UnsupportedOperationException();
1✔
593
  }
594

595
  @GuardedBy("evictionLock")
596
  protected void setMaximum(long maximum) {
597
    throw new UnsupportedOperationException();
1✔
598
  }
599

600
  @GuardedBy("evictionLock")
601
  protected void setWindowMaximum(long maximum) {
602
    throw new UnsupportedOperationException();
1✔
603
  }
604

605
  @GuardedBy("evictionLock")
606
  protected void setMainProtectedMaximum(long maximum) {
607
    throw new UnsupportedOperationException();
1✔
608
  }
609

610
  /** Returns the combined weight of the values in the cache (may be negative). */
611
  protected long weightedSize() {
612
    throw new UnsupportedOperationException();
1✔
613
  }
614

615
  /** Returns the combined weight of the values in the cache (may be negative). */
616
  protected long weightedSizeAcquire() {
617
    throw new UnsupportedOperationException();
1✔
618
  }
619

620
  /** Returns the uncorrected combined weight of the values in the window space. */
621
  protected long windowWeightedSize() {
622
    throw new UnsupportedOperationException();
1✔
623
  }
624

625
  /** Returns the uncorrected combined weight of the values in the main's protected space. */
626
  protected long mainProtectedWeightedSize() {
627
    throw new UnsupportedOperationException();
1✔
628
  }
629

630
  @GuardedBy("evictionLock")
631
  protected void setWeightedSize(long weightedSize) {
632
    throw new UnsupportedOperationException();
1✔
633
  }
634

635
  @GuardedBy("evictionLock")
636
  protected void setWindowWeightedSize(long weightedSize) {
637
    throw new UnsupportedOperationException();
1✔
638
  }
639

640
  @GuardedBy("evictionLock")
641
  protected void setMainProtectedWeightedSize(long weightedSize) {
642
    throw new UnsupportedOperationException();
1✔
643
  }
644

645
  protected long hitsInSample() {
646
    throw new UnsupportedOperationException();
1✔
647
  }
648

649
  protected long missesInSample() {
650
    throw new UnsupportedOperationException();
1✔
651
  }
652

653
  protected double stepSize() {
654
    throw new UnsupportedOperationException();
1✔
655
  }
656

657
  protected double previousSampleHitRate() {
658
    throw new UnsupportedOperationException();
1✔
659
  }
660

661
  protected long adjustment() {
662
    throw new UnsupportedOperationException();
1✔
663
  }
664

665
  @GuardedBy("evictionLock")
666
  protected void setHitsInSample(long hitCount) {
667
    throw new UnsupportedOperationException();
1✔
668
  }
669

670
  @GuardedBy("evictionLock")
671
  protected void setMissesInSample(long missCount) {
672
    throw new UnsupportedOperationException();
1✔
673
  }
674

675
  @GuardedBy("evictionLock")
676
  protected void setStepSize(double stepSize) {
677
    throw new UnsupportedOperationException();
1✔
678
  }
679

680
  @GuardedBy("evictionLock")
681
  protected void setPreviousSampleHitRate(double hitRate) {
682
    throw new UnsupportedOperationException();
1✔
683
  }
684

685
  @GuardedBy("evictionLock")
686
  protected void setAdjustment(long amount) {
687
    throw new UnsupportedOperationException();
1✔
688
  }
689

690
  /**
691
   * Sets the maximum weighted size of the cache. The caller may need to perform a maintenance cycle
692
   * to eagerly evicts entries until the cache shrinks to the appropriate size.
693
   */
694
  @GuardedBy("evictionLock")
695
  @SuppressWarnings({"ConstantValue", "Varifier"})
696
  void setMaximumSize(long maximum) {
697
    requireArgument(maximum >= 0, "maximum must not be negative");
1✔
698
    if (maximum == maximum()) {
1✔
699
      return;
1✔
700
    }
701

702
    var max = Math.min(maximum, MAXIMUM_CAPACITY);
1✔
703
    var window = max - (long) (PERCENT_MAIN * max);
1✔
704
    var mainProtected = (long) (PERCENT_MAIN_PROTECTED * (max - window));
1✔
705
    var stepSize = Math.max(HILL_CLIMBER_STEP_PERCENT * max, HILL_CLIMBER_MIN_INITIAL_STEP);
1✔
706

707
    setMaximum(max);
1✔
708
    setWindowMaximum(window);
1✔
709
    setMainProtectedMaximum(mainProtected);
1✔
710

711
    setHitsInSample(0);
1✔
712
    setMissesInSample(0);
1✔
713
    setStepSize((max <= SMALL_CACHE_THRESHOLD) ? stepSize : -stepSize);
1✔
714

715
    if ((frequencySketch() != null) && !isWeighted() && (weightedSize() >= (max >>> 1))) {
1✔
716
      // Lazily initialize when close to the maximum size
717
      frequencySketch().ensureCapacity(max);
1✔
718
    }
719
  }
1✔
720

721
  /** Evicts entries if the cache exceeds the maximum. */
722
  @GuardedBy("evictionLock")
723
  void evictEntries() {
724
    if (!evicts()) {
1✔
725
      return;
1✔
726
    }
727
    var candidate = evictFromWindow();
1✔
728
    evictFromMain(candidate);
1✔
729
  }
1✔
730

731
  /**
732
   * Evicts entries from the window space into the main space while the window size exceeds a
733
   * maximum.
734
   *
735
   * @return the first candidate promoted into the probation space
736
   */
737
  @GuardedBy("evictionLock")
738
  @Nullable Node<K, V> evictFromWindow() {
739
    @Var Node<K, V> first = null;
1✔
740
    @Var Node<K, V> node = accessOrderWindowDeque().peekFirst();
1✔
741
    while (windowWeightedSize() > windowMaximum()) {
1✔
742
      // The pending operations will adjust the size to reflect the correct weight
743
      if (node == null) {
1✔
744
        break;
1✔
745
      }
746

747
      Node<K, V> next = node.getNextInAccessOrder();
1✔
748
      if (node.getPolicyWeight() != 0) {
1✔
749
        node.makeMainProbation();
1✔
750
        accessOrderWindowDeque().remove(node);
1✔
751
        accessOrderProbationDeque().offerLast(node);
1✔
752
        if (first == null) {
1✔
753
          first = node;
1✔
754
        }
755

756
        setWindowWeightedSize(windowWeightedSize() - node.getPolicyWeight());
1✔
757
      }
758
      node = next;
1✔
759
    }
1✔
760

761
    return first;
1✔
762
  }
763

764
  /**
765
   * Evicts entries from the main space if the cache exceeds the maximum capacity. The main space
766
   * determines whether admitting an entry (coming from the window space) is preferable to retaining
767
   * the eviction policy's victim. This decision is made using a frequency filter so that the
768
   * least frequently used entry is removed.
769
   * <p>
770
   * The window space's candidates were previously promoted to the probation space at its MRU
771
   * position and the eviction policy's victim starts at the LRU position. The candidates are
772
   * evaluated in promotion order while an eviction is required, and if exhausted then additional
773
   * entries are retrieved from the window space. Likewise, if the victim selection exhausts the
774
   * probation space then additional entries are retrieved from the protected space. The queues are
775
   * consumed in LRU order and the evicted entry is the one with a lower relative frequency, where
776
   * the preference is to retain the main space's victims versus the window space's candidates on a
777
   * tie.
778
   *
779
   * @param candidate the first candidate promoted into the probation space
780
   */
781
  @GuardedBy("evictionLock")
782
  void evictFromMain(@Var @Nullable Node<K, V> candidate) {
783
    @Var int victimQueue = PROBATION;
1✔
784
    @Var int candidateQueue = PROBATION;
1✔
785
    @Var Node<K, V> victim = accessOrderProbationDeque().peekFirst();
1✔
786
    while (weightedSize() > maximum()) {
1✔
787
      // Search the admission window for additional candidates
788
      if ((candidate == null) && (candidateQueue == PROBATION)) {
1✔
789
        candidate = accessOrderWindowDeque().peekFirst();
1✔
790
        candidateQueue = WINDOW;
1✔
791
      }
792

793
      // Try evicting from the protected and window queues
794
      if ((candidate == null) && (victim == null)) {
1✔
795
        if (victimQueue == PROBATION) {
1✔
796
          victim = accessOrderProtectedDeque().peekFirst();
1✔
797
          victimQueue = PROTECTED;
1✔
798
          continue;
1✔
799
        } else if (victimQueue == PROTECTED) {
1✔
800
          victim = accessOrderWindowDeque().peekFirst();
1✔
801
          victimQueue = WINDOW;
1✔
802
          continue;
1✔
803
        }
804

805
        // The pending operations will adjust the size to reflect the correct weight
806
        break;
807
      }
808

809
      // Skip over entries with zero weight
810
      if ((victim != null) && (victim.getPolicyWeight() == 0)) {
1✔
811
        victim = victim.getNextInAccessOrder();
1✔
812
        continue;
1✔
813
      } else if ((candidate != null) && (candidate.getPolicyWeight() == 0)) {
1✔
814
        candidate = candidate.getNextInAccessOrder();
1✔
815
        continue;
1✔
816
      }
817

818
      // Evict immediately if only one of the entries is present
819
      if (victim == null) {
1✔
820
        requireNonNull(candidate);
1✔
821
        Node<K, V> previous = candidate.getNextInAccessOrder();
1✔
822
        Node<K, V> evict = candidate;
1✔
823
        candidate = previous;
1✔
824
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
825
        continue;
1✔
826
      } else if (candidate == null) {
1✔
827
        Node<K, V> evict = victim;
1✔
828
        victim = victim.getNextInAccessOrder();
1✔
829
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
830
        continue;
1✔
831
      }
832

833
      // Evict immediately if both selected the same entry
834
      if (candidate == victim) {
1✔
835
        victim = victim.getNextInAccessOrder();
1✔
836
        evictEntry(candidate, RemovalCause.SIZE, 0L);
1✔
837
        candidate = null;
1✔
838
        continue;
1✔
839
      }
840

841
      // Evict immediately if an entry was collected
842
      var victimKeyRef = victim.getKeyReferenceOrNull();
1✔
843
      var candidateKeyRef = candidate.getKeyReferenceOrNull();
1✔
844
      if (victimKeyRef == null) {
1✔
845
        Node<K, V> evict = victim;
1✔
846
        victim = victim.getNextInAccessOrder();
1✔
847
        evictEntry(evict, RemovalCause.COLLECTED, 0L);
1✔
848
        continue;
1✔
849
      } else if (candidateKeyRef == null) {
1✔
850
        Node<K, V> evict = candidate;
1✔
851
        candidate = candidate.getNextInAccessOrder();
1✔
852
        evictEntry(evict, RemovalCause.COLLECTED, 0L);
1✔
853
        continue;
1✔
854
      }
855

856
      // Evict immediately if an entry was removed
857
      if (!victim.isAlive()) {
1✔
858
        Node<K, V> evict = victim;
1✔
859
        victim = victim.getNextInAccessOrder();
1✔
860
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
861
        continue;
1✔
862
      } else if (!candidate.isAlive()) {
1✔
863
        Node<K, V> evict = candidate;
1✔
864
        candidate = candidate.getNextInAccessOrder();
1✔
865
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
866
        continue;
1✔
867
      }
868

869
      // Evict immediately if the candidate's weight exceeds the maximum
870
      if (candidate.getPolicyWeight() > maximum()) {
1✔
871
        Node<K, V> evict = candidate;
1✔
872
        candidate = candidate.getNextInAccessOrder();
1✔
873
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
874
        continue;
1✔
875
      }
876

877
      // Evict the entry with the lowest frequency
878
      if (admit(candidateKeyRef, victimKeyRef)) {
1✔
879
        Node<K, V> evict = victim;
1✔
880
        victim = victim.getNextInAccessOrder();
1✔
881
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
882
        candidate = candidate.getNextInAccessOrder();
1✔
883
      } else {
1✔
884
        Node<K, V> evict = candidate;
1✔
885
        candidate = candidate.getNextInAccessOrder();
1✔
886
        evictEntry(evict, RemovalCause.SIZE, 0L);
1✔
887
      }
888
    }
1✔
889
  }
1✔
890

891
  /**
892
   * Determines if the candidate should be accepted into the main space, as determined by its
893
   * frequency relative to the victim. A small amount of randomness is used to protect against hash
894
   * collision attacks, where the victim's frequency is artificially raised so that no new entries
895
   * are admitted.
896
   *
897
   * @param candidateKeyRef the keyRef for the entry being proposed for long term retention
898
   * @param victimKeyRef the keyRef for the entry chosen by the eviction policy for replacement
899
   * @return if the candidate should be admitted and the victim ejected
900
   */
901
  @GuardedBy("evictionLock")
902
  boolean admit(Object candidateKeyRef, Object victimKeyRef) {
903
    int candidateFreq = frequencySketch().frequency(candidateKeyRef);
1✔
904
    int victimFreq = frequencySketch().frequency(victimKeyRef);
1✔
905
    if (candidateFreq > victimFreq) {
1✔
906
      return true;
1✔
907
    } else if (candidateFreq >= ADMIT_HASHDOS_THRESHOLD) {
1✔
908
      // The maximum frequency is 15 and halved to 7 after a reset to age the history. An attack
909
      // exploits that a hot candidate is rejected in favor of a hot victim. The threshold of a warm
910
      // candidate reduces the number of random acceptances to minimize the impact on the hit rate.
911
      int random = ThreadLocalRandom.current().nextInt();
1✔
912
      return ((random & 127) == 0);
1✔
913
    }
914
    return false;
1✔
915
  }
916

917
  /** Expires entries that have expired by access, write, or variable. */
918
  @GuardedBy("evictionLock")
919
  void expireEntries() {
920
    long now = expirationTicker().read();
1✔
921
    expireAfterAccessEntries(now);
1✔
922
    expireAfterWriteEntries(now);
1✔
923
    expireVariableEntries(now);
1✔
924

925
    Pacer pacer = pacer();
1✔
926
    if (pacer != null) {
1✔
927
      long delay = getExpirationDelay(now);
1✔
928
      if (delay == Long.MAX_VALUE) {
1✔
929
        pacer.cancel();
1✔
930
      } else {
931
        pacer.schedule(executor, drainBuffersTask, now, delay);
1✔
932
      }
933
    }
934
  }
1✔
935

936
  /** Expires entries in the access-order queue. */
937
  @GuardedBy("evictionLock")
938
  void expireAfterAccessEntries(long now) {
939
    if (!expiresAfterAccess()) {
1✔
940
      return;
1✔
941
    }
942

943
    @Var int remaining = EXPIRATION_THRESHOLD;
1✔
944
    remaining = expireAfterAccessEntries(now, accessOrderWindowDeque(), remaining);
1✔
945
    if (evicts()) {
1✔
946
      remaining = expireAfterAccessEntries(now, accessOrderProbationDeque(), remaining);
1✔
947
      remaining = expireAfterAccessEntries(now, accessOrderProtectedDeque(), remaining);
1✔
948
    }
949
    if (remaining == 0) {
1✔
950
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1✔
951
    }
952
  }
1✔
953

954
  /**
955
   * Expires entries in an access-order queue, up to the {@code remaining} budget, and returns the
956
   * unused budget. When exhausted the caller re-arms maintenance to process the backlog.
957
   */
958
  @GuardedBy("evictionLock")
959
  int expireAfterAccessEntries(long now,
960
      AccessOrderDeque<Node<K, V>> accessOrderDeque, @Var int remaining) {
961
    var head = accessOrderDeque.peekFirst();
1✔
962
    if (head == null) {
1✔
963
      return remaining;
1✔
964
    }
965
    var duration = expiresAfterAccessNanos();
1✔
966
    var last = requireNonNull(accessOrderDeque.peekLast());
1✔
967
    for (var node = head; (node != null) && (remaining > 0);) {
1✔
968
      var next = (node == last) ? null : node.getNextInAccessOrder();
1✔
969
      if ((now - node.getAccessTime()) < duration) {
1✔
970
        var stalePosition = ((last.getAccessTime() - node.getAccessTime()) < 0);
1✔
971
        if (stalePosition || isComputingAsync(node.getValue())) {
1✔
972
          accessOrderDeque.moveToBack(node);
1✔
973
          node = next;
1✔
974
          continue;
1✔
975
        }
976
        return remaining;
1✔
977
      }
978
      evictEntry(node, RemovalCause.EXPIRED, now);
1✔
979
      remaining--;
1✔
980
      node = next;
1✔
981
    }
1✔
982
    return remaining;
1✔
983
  }
984

985
  /** Expires entries on the write-order queue. */
986
  @GuardedBy("evictionLock")
987
  void expireAfterWriteEntries(long now) {
988
    if (!expiresAfterWrite()) {
1✔
989
      return;
1✔
990
    }
991

992
    var head = writeOrderDeque().peekFirst();
1✔
993
    if (head == null) {
1✔
994
      return;
1✔
995
    }
996
    var duration = expiresAfterWriteNanos();
1✔
997
    @Var int remaining = EXPIRATION_THRESHOLD;
1✔
998
    var last = requireNonNull(writeOrderDeque().peekLast());
1✔
999
    for (var node = head; (node != null) && (remaining > 0);) {
1✔
1000
      var next = (node == last) ? null : node.getNextInWriteOrder();
1✔
1001
      if ((now - node.getWriteTime()) < duration) {
1✔
1002
        var stalePosition = ((last.getWriteTime() - node.getWriteTime()) < 0);
1✔
1003
        if (stalePosition || isComputingAsync(node.getValue())) {
1✔
1004
          writeOrderDeque().moveToBack(node);
1✔
1005
          node = next;
1✔
1006
          continue;
1✔
1007
        }
1008
        return;
1✔
1009
      }
1010
      evictEntry(node, RemovalCause.EXPIRED, now);
1✔
1011
      remaining--;
1✔
1012
      node = next;
1✔
1013
    }
1✔
1014
    if (remaining == 0) {
1✔
1015
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1✔
1016
    }
1017
  }
1✔
1018

1019
  /** Expires entries in the timer wheel. */
1020
  @GuardedBy("evictionLock")
1021
  void expireVariableEntries(long now) {
1022
    if (expiresVariable() && (timerWheel().advance(this, now, EXPIRATION_THRESHOLD) == 0)) {
1✔
1023
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1✔
1024
    }
1025
  }
1✔
1026

1027
  /** Returns the duration until the next item expires, or {@link Long#MAX_VALUE} if none. */
1028
  @GuardedBy("evictionLock")
1029
  long getExpirationDelay(long now) {
1030
    @Var long delay = Long.MAX_VALUE;
1✔
1031
    if (expiresAfterAccess()) {
1✔
1032
      @Var Node<K, V> node = accessOrderWindowDeque().peekFirst();
1✔
1033
      if (node != null) {
1✔
1034
        long age = Math.max(0, now - node.getAccessTime());
1✔
1035
        delay = Math.min(delay, expiresAfterAccessNanos() - age);
1✔
1036
      }
1037
      if (evicts()) {
1✔
1038
        node = accessOrderProbationDeque().peekFirst();
1✔
1039
        if (node != null) {
1✔
1040
          long age = Math.max(0, now - node.getAccessTime());
1✔
1041
          delay = Math.min(delay, expiresAfterAccessNanos() - age);
1✔
1042
        }
1043
        node = accessOrderProtectedDeque().peekFirst();
1✔
1044
        if (node != null) {
1✔
1045
          long age = Math.max(0, now - node.getAccessTime());
1✔
1046
          delay = Math.min(delay, expiresAfterAccessNanos() - age);
1✔
1047
        }
1048
      }
1049
    }
1050
    if (expiresAfterWrite()) {
1✔
1051
      Node<K, V> node = writeOrderDeque().peekFirst();
1✔
1052
      if (node != null) {
1✔
1053
        long age = Math.max(0, now - node.getWriteTime());
1✔
1054
        delay = Math.min(delay, expiresAfterWriteNanos() - age);
1✔
1055
      }
1056
    }
1057
    if (expiresVariable()) {
1✔
1058
      delay = Math.min(delay, timerWheel().getExpirationDelay());
1✔
1059
    }
1060
    return delay;
1✔
1061
  }
1062

1063
  /** Returns if the entry has expired. */
1064
  @SuppressWarnings("ShortCircuitBoolean")
1065
  boolean hasExpired(Node<K, V> node, long now, V value) {
1066
    if (isComputingAsync(value)) {
1✔
1067
      return false;
1✔
1068
    }
1069
    return (expiresAfterAccess() && (now - node.getAccessTime() >= expiresAfterAccessNanos()))
1✔
1070
        | (expiresAfterWrite() && (now - node.getWriteTime() >= expiresAfterWriteNanos()))
1✔
1071
        | (expiresVariable() && (now - node.getVariableTime() >= 0));
1✔
1072
  }
1073

1074
  /**
1075
   * Attempts to evict the entry based on the given removal cause. A removal may be ignored if the
1076
   * entry was updated and is no longer eligible for eviction.
1077
   *
1078
   * @param node the entry to evict
1079
   * @param cause the reason to evict
1080
   * @param now the current time, used only if expiring
1081
   * @return if the entry was evicted
1082
   */
1083
  @GuardedBy("evictionLock")
1084
  @SuppressWarnings({"GuardedByChecker", "SynchronizationOnLocalVariableOrMethodParameter"})
1085
  boolean evictEntry(Node<K, V> node, RemovalCause cause, long now) {
1086
    K key = node.getKey();
1✔
1087
    var ctx = new EvictContext<V>();
1✔
1088
    var keyReference = node.getKeyReference();
1✔
1089

1090
    data.computeIfPresent(keyReference, (k, n) -> {
1✔
1091
      if (n != node) {
1✔
1092
        return n;
1✔
1093
      }
1094
      synchronized (node) {
1✔
1095
        ctx.value = node.getValue();
1✔
1096

1097
        if ((key == null) || (ctx.value == null)) {
1✔
1098
          ctx.cause = RemovalCause.COLLECTED;
1✔
1099
        } else if (cause == RemovalCause.COLLECTED) {
1✔
1100
          ctx.resurrect = true;
1✔
1101
          return node;
1✔
1102
        } else {
1103
          ctx.cause = cause;
1✔
1104
        }
1105

1106
        if (ctx.cause == RemovalCause.EXPIRED) {
1✔
1107
          @Var boolean expired = false;
1✔
1108
          if (expiresAfterAccess()) {
1✔
1109
            expired |= ((now - node.getAccessTime()) >= expiresAfterAccessNanos());
1✔
1110
          }
1111
          if (expiresAfterWrite()) {
1✔
1112
            expired |= ((now - node.getWriteTime()) >= expiresAfterWriteNanos());
1✔
1113
          }
1114
          if (expiresVariable()) {
1✔
1115
            expired |= ((now - node.getVariableTime()) >= 0);
1✔
1116
          }
1117
          if (expired) {
1✔
1118
            if (isComputingAsync(ctx.value)) {
1✔
1119
              long sentinel = (now + ASYNC_EXPIRY);
1✔
1120
              setVariableTime(node, sentinel);
1✔
1121
              setAccessTime(node, sentinel);
1✔
1122
              setWriteTime(node, sentinel);
1✔
1123
              ctx.resurrect = true;
1✔
1124
              return node;
1✔
1125
            }
1126
          } else {
1127
            ctx.resurrect = true;
1✔
1128
            return node;
1✔
1129
          }
1130
        } else if (ctx.cause == RemovalCause.SIZE) {
1✔
1131
          int weight = node.getWeight();
1✔
1132
          if (weight == 0) {
1✔
1133
            ctx.resurrect = true;
1✔
1134
            return node;
1✔
1135
          }
1136
        }
1137

1138
        notifyEviction(key, ctx.value, ctx.cause);
1✔
1139
        discardRefresh(keyReference);
1✔
1140
        ctx.removed = true;
1✔
1141
        node.retire();
1✔
1142
        return null;
1✔
1143
      }
1144
    });
1145

1146
    // The entry is no longer eligible for eviction
1147
    if (ctx.resurrect) {
1✔
1148
      return false;
1✔
1149
    }
1150

1151
    // If the eviction fails due to a concurrent removal of the victim, that removal may cancel out
1152
    // the addition that triggered this eviction. The victim is eagerly unlinked and the size
1153
    // decremented before the removal task so that if an eviction is still required then a new
1154
    // victim will be chosen for removal.
1155
    if (node.inWindow() && (evicts() || expiresAfterAccess())) {
1✔
1156
      accessOrderWindowDeque().remove(node);
1✔
1157
    } else if (evicts()) {
1✔
1158
      if (node.inMainProbation()) {
1✔
1159
        accessOrderProbationDeque().remove(node);
1✔
1160
      } else {
1161
        accessOrderProtectedDeque().remove(node);
1✔
1162
      }
1163
    }
1164
    if (expiresAfterWrite()) {
1✔
1165
      writeOrderDeque().remove(node);
1✔
1166
    } else if (expiresVariable()) {
1✔
1167
      timerWheel().deschedule(node);
1✔
1168
    }
1169

1170
    synchronized (node) {
1✔
1171
      logIfAlive(node);
1✔
1172
      makeDead(node);
1✔
1173
    }
1✔
1174

1175
    if (ctx.removed) {
1✔
1176
      var removeCause = requireNonNull(ctx.cause);
1✔
1177
      statsCounter().recordEviction(node.getWeight(), removeCause);
1✔
1178
      notifyRemoval(key, ctx.value, removeCause);
1✔
1179
    }
1180

1181
    return true;
1✔
1182
  }
1183

1184
  /** Adapts the eviction policy to towards the optimal recency / frequency configuration. */
1185
  @GuardedBy("evictionLock")
1186
  @SuppressWarnings("UnnecessaryReturnStatement")
1187
  void climb() {
1188
    if (!evicts()) {
1✔
1189
      return;
1✔
1190
    }
1191
    determineAdjustment();
1✔
1192
    demoteFromMainProtected();
1✔
1193
    long amount = adjustment();
1✔
1194
    if (amount == 0) {
1✔
1195
      return;
1✔
1196
    } else if (amount > 0) {
1✔
1197
      increaseWindow();
1✔
1198
    } else {
1199
      decreaseWindow();
1✔
1200
    }
1201
  }
1✔
1202

1203
  /** Calculates the amount to adapt the window by and sets {@link #adjustment()} accordingly. */
1204
  @GuardedBy("evictionLock")
1205
  @SuppressWarnings("MathClampDouble")
1206
  void determineAdjustment() {
1207
    if (frequencySketch().isNotInitialized()) {
1✔
1208
      setPreviousSampleHitRate(0.0);
1✔
1209
      setMissesInSample(0);
1✔
1210
      setHitsInSample(0);
1✔
1211
      return;
1✔
1212
    }
1213

1214
    long requestCount = hitsInSample() + missesInSample();
1✔
1215
    @Var double stepDecayRate = HILL_CLIMBER_STEP_DECAY_RATE;
1✔
1216
    @Var long effectiveSampleSize = frequencySketch().sampleSize;
1✔
1217
    if (maximum() <= SMALL_CACHE_THRESHOLD) {
1✔
1218
      // Grows the sample period as the step size decays to avoid converging near the initial ratio
1219
      double initialStep = HILL_CLIMBER_STEP_PERCENT * maximum();
1✔
1220
      double magnitude = Math.max(initialStep / SMALL_CACHE_SAMPLE_RATIO_CAP, Math.abs(stepSize()));
1✔
1221
      double ratio = (magnitude == 0.0)
1✔
1222
          ? 1.0
1✔
1223
          : Math.max(1.0, Math.min(SMALL_CACHE_SAMPLE_RATIO_CAP, initialStep / magnitude));
1✔
1224
      effectiveSampleSize = (long) (effectiveSampleSize * ratio);
1✔
1225
      stepDecayRate = SMALL_CACHE_STEP_DECAY_RATE;
1✔
1226
    }
1227
    if (requestCount < effectiveSampleSize) {
1✔
1228
      return;
1✔
1229
    }
1230

1231
    double hitRate = (double) hitsInSample() / requestCount;
1✔
1232
    double hitRateChange = hitRate - previousSampleHitRate();
1✔
1233
    double amount = (hitRateChange >= 0) ? stepSize() : -stepSize();
1✔
1234
    double nextStepSize = (Math.abs(hitRateChange) >= HILL_CLIMBER_RESTART_THRESHOLD)
1✔
1235
        ? Math.copySign(
1✔
1236
            Math.max(HILL_CLIMBER_STEP_PERCENT * maximum(), HILL_CLIMBER_MIN_INITIAL_STEP), amount)
1✔
1237
        : (stepDecayRate * amount);
1✔
1238
    setPreviousSampleHitRate(hitRate);
1✔
1239
    setAdjustment((long) amount);
1✔
1240
    setStepSize(nextStepSize);
1✔
1241
    setMissesInSample(0);
1✔
1242
    setHitsInSample(0);
1✔
1243
  }
1✔
1244

1245
  /**
1246
   * Increases the size of the admission window by shrinking the portion allocated to the main
1247
   * space. As the main space is partitioned into probation and protected regions (80% / 20%), for
1248
   * simplicity only the protected is reduced. If the regions exceed their maximums, this may cause
1249
   * protected items to be demoted to the probation region and probation items to be demoted to the
1250
   * admission window.
1251
   */
1252
  @GuardedBy("evictionLock")
1253
  void increaseWindow() {
1254
    if (mainProtectedMaximum() == 0) {
1✔
1255
      return;
1✔
1256
    }
1257

1258
    @SuppressWarnings("MathClampLong")
1259
    @Var long quota = Math.min(adjustment(), mainProtectedMaximum());
1✔
1260
    setMainProtectedMaximum(mainProtectedMaximum() - quota);
1✔
1261
    setWindowMaximum(windowMaximum() + quota);
1✔
1262
    demoteFromMainProtected();
1✔
1263

1264
    for (int i = 0; i < QUEUE_TRANSFER_THRESHOLD; i++) {
1✔
1265
      @Var Node<K, V> candidate = accessOrderProbationDeque().peekFirst();
1✔
1266
      @Var boolean probation = true;
1✔
1267
      if ((candidate == null) || (quota < candidate.getPolicyWeight())) {
1✔
1268
        candidate = accessOrderProtectedDeque().peekFirst();
1✔
1269
        probation = false;
1✔
1270
      }
1271
      if (candidate == null) {
1✔
1272
        break;
1✔
1273
      }
1274

1275
      int weight = candidate.getPolicyWeight();
1✔
1276
      if (quota < weight) {
1✔
1277
        break;
1✔
1278
      }
1279

1280
      quota -= weight;
1✔
1281
      if (probation) {
1✔
1282
        accessOrderProbationDeque().remove(candidate);
1✔
1283
      } else {
1284
        setMainProtectedWeightedSize(mainProtectedWeightedSize() - weight);
1✔
1285
        accessOrderProtectedDeque().remove(candidate);
1✔
1286
      }
1287
      setWindowWeightedSize(windowWeightedSize() + weight);
1✔
1288
      accessOrderWindowDeque().offerLast(candidate);
1✔
1289
      candidate.makeWindow();
1✔
1290
    }
1291

1292
    setMainProtectedMaximum(mainProtectedMaximum() + quota);
1✔
1293
    setWindowMaximum(windowMaximum() - quota);
1✔
1294
    setAdjustment(quota);
1✔
1295
  }
1✔
1296

1297
  /** Decreases the size of the admission window and increases the main's protected region. */
1298
  @GuardedBy("evictionLock")
1299
  void decreaseWindow() {
1300
    if (windowMaximum() <= 1) {
1✔
1301
      return;
1✔
1302
    }
1303

1304
    @SuppressWarnings("MathClampLong")
1305
    @Var long quota = Math.min(-adjustment(), Math.max(0, windowMaximum() - 1));
1✔
1306
    setMainProtectedMaximum(mainProtectedMaximum() + quota);
1✔
1307
    setWindowMaximum(windowMaximum() - quota);
1✔
1308

1309
    for (int i = 0; i < QUEUE_TRANSFER_THRESHOLD; i++) {
1✔
1310
      Node<K, V> candidate = accessOrderWindowDeque().peekFirst();
1✔
1311
      if (candidate == null) {
1✔
1312
        break;
1✔
1313
      }
1314

1315
      int weight = candidate.getPolicyWeight();
1✔
1316
      if (quota < weight) {
1✔
1317
        break;
1✔
1318
      }
1319

1320
      quota -= weight;
1✔
1321
      setWindowWeightedSize(windowWeightedSize() - weight);
1✔
1322
      accessOrderWindowDeque().remove(candidate);
1✔
1323
      accessOrderProbationDeque().offerLast(candidate);
1✔
1324
      candidate.makeMainProbation();
1✔
1325
    }
1326

1327
    setMainProtectedMaximum(mainProtectedMaximum() - quota);
1✔
1328
    setWindowMaximum(windowMaximum() + quota);
1✔
1329
    setAdjustment(-quota);
1✔
1330
  }
1✔
1331

1332
  /** Transfers the nodes from the protected to the probation region if it exceeds the maximum. */
1333
  @GuardedBy("evictionLock")
1334
  void demoteFromMainProtected() {
1335
    long mainProtectedMaximum = mainProtectedMaximum();
1✔
1336
    @Var long mainProtectedWeightedSize = mainProtectedWeightedSize();
1✔
1337
    if (mainProtectedWeightedSize <= mainProtectedMaximum) {
1✔
1338
      return;
1✔
1339
    }
1340

1341
    for (int i = 0; i < QUEUE_TRANSFER_THRESHOLD; i++) {
1✔
1342
      if (mainProtectedWeightedSize <= mainProtectedMaximum) {
1✔
1343
        break;
1✔
1344
      }
1345

1346
      Node<K, V> demoted = accessOrderProtectedDeque().pollFirst();
1✔
1347
      if (demoted == null) {
1✔
1348
        break;
1✔
1349
      }
1350
      demoted.makeMainProbation();
1✔
1351
      accessOrderProbationDeque().offerLast(demoted);
1✔
1352
      mainProtectedWeightedSize -= demoted.getPolicyWeight();
1✔
1353
    }
1354
    setMainProtectedWeightedSize(mainProtectedWeightedSize);
1✔
1355
  }
1✔
1356

1357
  /**
1358
   * Performs the post-processing work required after a read.
1359
   *
1360
   * @param node the entry in the page replacement policy
1361
   * @param now the current time, in nanoseconds
1362
   * @param recordHit if the hit count should be incremented
1363
   * @return the refreshed value if immediately loaded, else null
1364
   */
1365
  @Nullable V afterRead(Node<K, V> node, long now, boolean recordHit) {
1366
    if (recordHit) {
1✔
1367
      statsCounter().recordHits(1);
1✔
1368
    }
1369

1370
    boolean delayable = skipReadBuffer() || (readBuffer.offer(node) != Buffer.FULL);
1✔
1371
    if (shouldDrainBuffers(delayable)) {
1✔
1372
      scheduleDrainBuffers();
1✔
1373
    }
1374
    return refreshIfNeeded(node, now);
1✔
1375
  }
1376

1377
  /** Returns if the cache should bypass the read buffer. */
1378
  boolean skipReadBuffer() {
1379
    return fastpath() && frequencySketch().isNotInitialized();
1✔
1380
  }
1381

1382
  /**
1383
   * Asynchronously refreshes the entry if eligible.
1384
   *
1385
   * @param node the entry in the cache to refresh
1386
   * @param now the current time, in nanoseconds
1387
   * @return the refreshed value if immediately loaded, else null
1388
   */
1389
  @SuppressWarnings("FutureReturnValueIgnored")
1390
  @Nullable V refreshIfNeeded(Node<K, V> node, long now) {
1391
    if (!refreshAfterWrite()) {
1✔
1392
      return null;
1✔
1393
    }
1394

1395
    K key;
1396
    V oldValue;
1397
    Object keyReference;
1398
    long writeTime = node.getWriteTime();
1✔
1399
    long refreshWriteTime = writeTime | 1L;
1✔
1400
    ConcurrentMap<Object, CompletableFuture<?>> refreshes;
1401
    if (((now - writeTime) > refreshAfterWriteNanos())
1✔
1402
        && ((key = node.getKey()) != null) && ((oldValue = node.getValue()) != null)
1✔
1403
        && !isComputingAsync(oldValue) && ((writeTime & 1L) == 0L)
1✔
1404
        && !(refreshes = refreshes()).containsKey(keyReference = node.getKeyReference())
1✔
1405
        && node.isAlive() && node.casWriteTime(writeTime, refreshWriteTime)) {
1✔
1406
      long[] startTime = new long[1];
1✔
1407
      @SuppressWarnings({"rawtypes", "unchecked"})
1408
      @Nullable CompletableFuture<? extends @Nullable V>[] refreshFuture = new CompletableFuture[1];
1✔
1409
      try {
1410
        refreshes.computeIfAbsent(keyReference, k -> {
1✔
1411
          if (!node.isAlive() || (node.getWriteTime() != refreshWriteTime)) {
1✔
1412
            return null;
1✔
1413
          }
1414
          try {
1415
            startTime[0] = statsTicker().read();
1✔
1416
            if (isAsync) {
1✔
1417
              @SuppressWarnings("unchecked")
1418
              var future = (CompletableFuture<V>) oldValue;
1✔
1419
              if (Async.isReady(future)) {
1✔
1420
                requireNonNull(cacheLoader);
1✔
1421
                var refresh = cacheLoader.asyncReload(key, future.join(), executor);
1✔
1422
                refreshFuture[0] = requireNonNull(refresh, "Null future");
1✔
1423
              } else {
1✔
1424
                // no-op if the future's completion state was modified (e.g. obtrude methods)
1425
                return null;
1✔
1426
              }
1427
            } else {
1✔
1428
              requireNonNull(cacheLoader);
1✔
1429
              var refresh = cacheLoader.asyncReload(key, oldValue, executor);
1✔
1430
              refreshFuture[0] = requireNonNull(refresh, "Null future");
1✔
1431
            }
1432
            return refreshFuture[0];
1✔
1433
          } catch (InterruptedException e) {
1✔
1434
            Thread.currentThread().interrupt();
1✔
1435
            logger.log(Level.WARNING, "Exception thrown when submitting refresh task", e);
1✔
1436
            return null;
1✔
1437
          } catch (Throwable e) {
1✔
1438
            logger.log(Level.WARNING, "Exception thrown when submitting refresh task", e);
1✔
1439
            return null;
1✔
1440
          }
1441
        });
1442
      } finally {
1443
        node.casWriteTime(refreshWriteTime, writeTime);
1✔
1444
      }
1445

1446
      if (refreshFuture[0] == null) {
1✔
1447
        return null;
1✔
1448
      }
1449

1450
      var refreshed = refreshFuture[0].handle((newValue, error) -> {
1✔
1451
        long loadTime = statsTicker().read() - startTime[0];
1✔
1452
        if (error != null) {
1✔
1453
          if (!(error instanceof CancellationException) && !(error instanceof TimeoutException)) {
1✔
1454
            logger.log(Level.WARNING, "Exception thrown during refresh", error);
1✔
1455
          }
1456
          refreshes.remove(keyReference, refreshFuture[0]);
1✔
1457
          statsCounter().recordLoadFailure(loadTime);
1✔
1458
          return null;
1✔
1459
        }
1460

1461
        @SuppressWarnings("unchecked")
1462
        V value = (isAsync && (newValue != null)) ? (V) refreshFuture[0] : newValue;
1✔
1463
        @Nullable RemovalCause[] cause = new RemovalCause[1];
1✔
1464
        var hints = new RemapHints();
1✔
1465
        @Nullable V result;
1466
        try {
1467
          result = compute(key, (K k, @Nullable V currentValue) -> {
1✔
1468
            // Keep the refresh registered until the write clears it to avoid readers from
1469
            // prematurely scheduling another reload
1470
            if (currentValue == null) {
1✔
1471
              // If the entry is absent then discard the refresh and maybe notify the listener
1472
              if (value != null) {
1✔
1473
                cause[0] = RemovalCause.EXPLICIT;
1✔
1474
              }
1475
              return null;
1✔
1476
            } else if (currentValue == value) {
1✔
1477
              // If the reloaded value is the same instance then no-op
1478
              return currentValue;
1✔
1479
            } else if (isAsync &&
1✔
1480
                (newValue == Async.getIfReady((CompletableFuture<?>) currentValue))) {
1✔
1481
              // If the completed futures hold the same value instance then no-op
1482
              return currentValue;
1✔
1483
            } else if ((currentValue == oldValue) && ((node.getWriteTime() & ~1L) == writeTime)
1✔
1484
                && (refreshes.get(keyReference) == refreshFuture[0])) {
1✔
1485
              // If the entry was not modified while in-flight (no ABA) then replace
1486
              return value;
1✔
1487
            }
1488
            // Otherwise the refresh is discarded. If a concurrent write changed the value or
1489
            // writeTime, preserve those timestamps so the refresh rejection does not stomp on
1490
            // the user's write. An external discard with no concurrent write falls through to the
1491
            // normal update, which debounces the next refresh attempt.
1492
            if (value != null) {
1✔
1493
              cause[0] = RemovalCause.REPLACED;
1✔
1494
            }
1495
            if ((currentValue != oldValue) || ((node.getWriteTime() & ~1L) != writeTime)) {
1✔
1496
              hints.preserveTimestamps = true;
1✔
1497
            }
1498
            return currentValue;
1✔
1499
          }, expiry(), /* recordLoad= */ false, /* recordLoadFailure= */ true, hints);
1✔
1500
        } catch (Throwable t) {
1✔
1501
          logger.log(Level.WARNING, "Exception thrown during refresh", t);
1✔
1502
          statsCounter().recordLoadFailure(loadTime);
1✔
1503
          return null;
1✔
1504
        }
1✔
1505

1506
        if (cause[0] != null) {
1✔
1507
          notifyRemoval(key, value, cause[0]);
1✔
1508
        }
1509
        if (newValue == null) {
1✔
1510
          statsCounter().recordLoadFailure(loadTime);
1✔
1511
        } else {
1512
          statsCounter().recordLoadSuccess(loadTime);
1✔
1513
        }
1514
        return result;
1✔
1515
      });
1516
      return Async.getIfReady(refreshed);
1✔
1517
    }
1518

1519
    return null;
1✔
1520
  }
1521

1522
  /**
1523
   * Returns the expiration time for the entry after being created.
1524
   *
1525
   * @param key the key of the entry that was created
1526
   * @param value the value of the entry that was created
1527
   * @param expiry the calculator for the expiration time
1528
   * @param now the current time, in nanoseconds
1529
   * @return the expiration time
1530
   */
1531
  long expireAfterCreate(K key, V value, @Nullable Expiry<? super K, ? super V> expiry, long now) {
1532
    if (expiresVariable()) {
1✔
1533
      requireNonNull(expiry);
1✔
1534
      long duration = Math.max(0L, expiry.expireAfterCreate(key, value, now));
1✔
1535
      return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
1✔
1536
    }
1537
    return 0L;
1✔
1538
  }
1539

1540
  /**
1541
   * Returns the expiration time for the entry after being updated.
1542
   *
1543
   * @param node the entry in the page replacement policy
1544
   * @param key the key of the entry that was updated
1545
   * @param value the value of the entry that was updated
1546
   * @param expiry the calculator for the expiration time
1547
   * @param now the current time, in nanoseconds
1548
   * @return the expiration time
1549
   */
1550
  long expireAfterUpdate(Node<K, V> node, K key, V value,
1551
      @Nullable Expiry<? super K, ? super V> expiry, long now) {
1552
    if (expiresVariable()) {
1✔
1553
      requireNonNull(expiry);
1✔
1554
      long currentDuration = Math.max(1, node.getVariableTime() - now);
1✔
1555
      long duration = Math.max(0L, expiry.expireAfterUpdate(key, value, now, currentDuration));
1✔
1556
      return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
1✔
1557
    }
1558
    return 0L;
1✔
1559
  }
1560

1561
  /**
1562
   * Returns the access time for the entry after a read.
1563
   *
1564
   * @param node the entry in the page replacement policy
1565
   * @param key the key of the entry that was read
1566
   * @param value the value of the entry that was read
1567
   * @param expiry the calculator for the expiration time
1568
   * @param now the current time, in nanoseconds
1569
   * @return the expiration time
1570
   */
1571
  long expireAfterRead(Node<K, V> node, K key, V value, Expiry<K, V> expiry, long now) {
1572
    if (expiresVariable()) {
1✔
1573
      long currentDuration = Math.max(0L, node.getVariableTime() - now);
1✔
1574
      long duration = Math.max(0L, expiry.expireAfterRead(key, value, now, currentDuration));
1✔
1575
      return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
1✔
1576
    }
1577
    return 0L;
1✔
1578
  }
1579

1580
  /**
1581
   * Attempts to update the access time for the entry after a read.
1582
   *
1583
   * @param node the entry in the page replacement policy
1584
   * @param key the key of the entry that was read
1585
   * @param value the value of the entry that was read
1586
   * @param expiry the calculator for the expiration time
1587
   * @param now the current time, in nanoseconds
1588
   */
1589
  void tryExpireAfterRead(Node<K, V> node, K key, V value, Expiry<K, V> expiry, long now) {
1590
    if (!expiresVariable()) {
1✔
1591
      return;
1✔
1592
    }
1593

1594
    long variableTime = node.getVariableTime();
1✔
1595
    long currentDuration = Math.max(1, variableTime - now);
1✔
1596
    if (isAsync && (currentDuration > MAXIMUM_EXPIRY)) {
1✔
1597
      // expireAfterCreate has not yet set the duration after completion
1598
      return;
1✔
1599
    }
1600

1601
    long tolerance = EXPIRE_TOLERANCE;
1✔
1602
    long duration = Math.max(0L, expiry.expireAfterRead(key, value, now, currentDuration));
1✔
1603
    long expirationTime = isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
1✔
1604
    if ((duration <= tolerance) || (Math.abs(expirationTime - variableTime) > tolerance)) {
1✔
1605
      node.casVariableTime(variableTime, expirationTime);
1✔
1606
    }
1607
  }
1✔
1608

1609
  void setVariableTime(Node<K, V> node, long expirationTime) {
1610
    if (expiresVariable()) {
1✔
1611
      node.setVariableTime(expirationTime);
1✔
1612
    }
1613
  }
1✔
1614

1615
  void setWriteTime(Node<K, V> node, long now) {
1616
    if (expiresAfterWrite() || refreshAfterWrite()) {
1✔
1617
      node.setWriteTime(now & ~1L);
1✔
1618
    }
1619
  }
1✔
1620

1621
  void setAccessTime(Node<K, V> node, long now) {
1622
    if (!expiresAfterAccess()) {
1✔
1623
      return;
1✔
1624
    }
1625
    long tolerance = EXPIRE_TOLERANCE;
1✔
1626
    long accessTime = node.getAccessTime();
1✔
1627
    if ((expiresAfterAccessNanos() <= tolerance) || (Math.abs(now - accessTime) > tolerance)) {
1✔
1628
      node.setAccessTime(now);
1✔
1629
    }
1630
  }
1✔
1631

1632
  /** Returns if the entry's write time would exceed the minimum expiration reorder threshold. */
1633
  boolean exceedsWriteTimeTolerance(Node<K, V> node, long varTime, long now) {
1634
    long variableTime = node.getVariableTime();
1✔
1635
    long writeTime = node.getWriteTime();
1✔
1636
    long tolerance = EXPIRE_TOLERANCE;
1✔
1637
    return
1✔
1638
        (expiresAfterWrite()
1✔
1639
            && ((expiresAfterWriteNanos() <= tolerance) || (Math.abs(now - writeTime) > tolerance)))
1✔
1640
        || (refreshAfterWrite()
1✔
1641
            && ((refreshAfterWriteNanos() <= tolerance) || (Math.abs(now - writeTime) > tolerance)))
1✔
1642
        || (expiresVariable() && (Math.abs(varTime - variableTime) > tolerance));
1✔
1643
  }
1644

1645
  /**
1646
   * Performs the post-processing work required after a write.
1647
   *
1648
   * @param task the pending operation to be applied
1649
   */
1650
  void afterWrite(Runnable task) {
1651
    if (writeBuffer.offer(task)) {
1✔
1652
      scheduleAfterWrite();
1✔
1653
      return;
1✔
1654
    }
1655

1656
    // In scenarios where the writing threads cannot make progress then they attempt to provide
1657
    // assistance by performing the eviction work directly. This can resolve cases where the
1658
    // maintenance task is scheduled but not running. That might occur due to all of the executor's
1659
    // threads being busy (perhaps writing into this cache), the write rate greatly exceeds the
1660
    // consuming rate, priority inversion, or if the executor silently discarded the maintenance
1661
    // task. Unfortunately this cannot resolve when the eviction is blocked waiting on a long-
1662
    // running computation due to an eviction listener, the victim is being computed on by a writer,
1663
    // or the victim residing in the same hash bin as a computing entry. In those cases a warning is
1664
    // logged to encourage the application to decouple these computations from the map operations.
1665
    lock();
1✔
1666
    try {
1667
      maintenance(task);
1✔
1668
    } catch (RuntimeException e) {
1✔
1669
      logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", e);
1✔
1670
    } finally {
1671
      evictionLock.unlock();
1✔
1672
    }
1673
    rescheduleCleanUpIfIncomplete();
1✔
1674
  }
1✔
1675

1676
  /** Acquires the eviction lock. */
1677
  void lock() {
1678
    @Var long remainingNanos = WARN_AFTER_LOCK_WAIT_NANOS;
1✔
1679
    long end = System.nanoTime() + remainingNanos;
1✔
1680
    @Var boolean interrupted = false;
1✔
1681
    try {
1682
      for (;;) {
1683
        try {
1684
          if (evictionLock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
1✔
1685
            return;
1✔
1686
          }
1687
          logger.log(Level.WARNING, "The cache is experiencing excessive wait times for acquiring "
1✔
1688
              + "the eviction lock. This may indicate that a long-running computation has halted "
1689
              + "eviction when trying to remove the victim entry. Consider using AsyncCache to "
1690
              + "decouple the computation from the map operation.", new TimeoutException());
1691
          evictionLock.lock();
1✔
1692
          return;
1✔
1693
        } catch (InterruptedException e) {
1✔
1694
          remainingNanos = end - System.nanoTime();
1✔
1695
          interrupted = true;
1✔
1696
        }
1✔
1697
      }
1698
    } finally {
1699
      if (interrupted) {
1✔
1700
        Thread.currentThread().interrupt();
1✔
1701
      }
1702
    }
1703
  }
1704

1705
  /**
1706
   * Conditionally schedules the asynchronous maintenance task after a write operation. If the
1707
   * task status was IDLE or REQUIRED then the maintenance task is scheduled immediately. If it
1708
   * is already processing then it is set to transition to REQUIRED upon completion so that a new
1709
   * execution is triggered by the next operation.
1710
   */
1711
  void scheduleAfterWrite() {
1712
    @Var int drainStatus = drainStatusOpaque();
1✔
1713
    for (;;) {
1714
      switch (drainStatus) {
1✔
1715
        case IDLE:
1716
          casDrainStatus(IDLE, REQUIRED);
1✔
1717
          scheduleDrainBuffers();
1✔
1718
          return;
1✔
1719
        case REQUIRED:
1720
          scheduleDrainBuffers();
1✔
1721
          return;
1✔
1722
        case PROCESSING_TO_IDLE:
1723
          if (casDrainStatus(PROCESSING_TO_IDLE, PROCESSING_TO_REQUIRED)) {
1✔
1724
            return;
1✔
1725
          }
1726
          drainStatus = drainStatusAcquire();
1✔
1727
          continue;
1✔
1728
        case PROCESSING_TO_REQUIRED:
1729
          return;
1✔
1730
        default:
1731
          throw new IllegalStateException("Invalid drain status: " + drainStatus);
1✔
1732
      }
1733
    }
1734
  }
1735

1736
  /**
1737
   * Attempts to schedule an asynchronous task to apply the pending operations to the page
1738
   * replacement policy. If the executor rejects the task then it is run directly.
1739
   */
1740
  void scheduleDrainBuffers() {
1741
    if (drainStatusOpaque() >= PROCESSING_TO_IDLE) {
1✔
1742
      return;
1✔
1743
    }
1744
    if (evictionLock.tryLock()) {
1✔
1745
      try {
1746
        int drainStatus = drainStatusOpaque();
1✔
1747
        if (drainStatus >= PROCESSING_TO_IDLE) {
1✔
1748
          return;
1✔
1749
        }
1750
        setDrainStatusRelease(PROCESSING_TO_IDLE);
1✔
1751
        executor.execute(drainBuffersTask);
1✔
1752
      } catch (Throwable t) {
1✔
1753
        logger.log(Level.WARNING, "Exception thrown when submitting maintenance task", t);
1✔
1754
        maintenance(/* ignored */ null);
1✔
1755
      } finally {
1756
        evictionLock.unlock();
1✔
1757
      }
1758
    }
1759
  }
1✔
1760

1761
  @Override
1762
  public void cleanUp() {
1763
    try {
1764
      performCleanUp(/* ignored */ null);
1✔
1765
    } catch (RuntimeException e) {
1✔
1766
      logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", e);
1✔
1767
    }
1✔
1768
  }
1✔
1769

1770
  /**
1771
   * Performs the maintenance work, blocking until the lock is acquired.
1772
   *
1773
   * @param task an additional pending task to run, or {@code null} if not present
1774
   */
1775
  void performCleanUp(@Nullable Runnable task) {
1776
    evictionLock.lock();
1✔
1777
    try {
1778
      maintenance(task);
1✔
1779
    } finally {
1780
      evictionLock.unlock();
1✔
1781
    }
1782
    rescheduleCleanUpIfIncomplete();
1✔
1783
  }
1✔
1784

1785
  /**
1786
   * If there remains pending operations that were not handled by the prior clean up then try to
1787
   * schedule an asynchronous maintenance task. This may occur due to a concurrent write after the
1788
   * maintenance work had started or if the amortized threshold of work per clean up was reached.
1789
   */
1790
  @SuppressWarnings("resource")
1791
  void rescheduleCleanUpIfIncomplete() {
1792
    if (drainStatusOpaque() != REQUIRED) {
1✔
1793
      return;
1✔
1794
    }
1795

1796
    // An immediate scheduling cannot be performed on a custom executor because it may use a
1797
    // caller-runs policy. This could cause the caller's penalty to exceed the amortized threshold,
1798
    // e.g. repeated concurrent writes could result in a retry loop.
1799
    if (executor == ForkJoinPool.commonPool()) {
1✔
1800
      scheduleDrainBuffers();
1✔
1801
      return;
1✔
1802
    }
1803

1804
    // If a scheduler was configured then the maintenance can be deferred onto the custom executor
1805
    // and run in the near future. Otherwise, it will be handled due to other cache activity.
1806
    var pacer = pacer();
1✔
1807
    if ((pacer != null) && !pacer.isScheduled() && evictionLock.tryLock()) {
1✔
1808
      try {
1809
        if ((drainStatusOpaque() == REQUIRED) && !pacer.isScheduled()) {
1✔
1810
          pacer.schedule(executor, drainBuffersTask, expirationTicker().read(), Pacer.TOLERANCE);
1✔
1811
        }
1812
      } finally {
1813
        evictionLock.unlock();
1✔
1814
      }
1815
    }
1816
  }
1✔
1817

1818
  /**
1819
   * Performs the pending maintenance work and sets the state flags during processing to avoid
1820
   * excess scheduling attempts. The read buffer, write buffer, and reference queues are drained,
1821
   * followed by expiration, and size-based eviction.
1822
   *
1823
   * @param task an additional pending task to run, or {@code null} if not present
1824
   */
1825
  @GuardedBy("evictionLock")
1826
  void maintenance(@Nullable Runnable task) {
1827
    setDrainStatusRelease(PROCESSING_TO_IDLE);
1✔
1828

1829
    try {
1830
      try {
1831
        drainReadBuffer();
1✔
1832
        drainWriteBuffer();
1✔
1833
      } finally {
1834
        if (task != null) {
1✔
1835
          task.run();
1✔
1836
        }
1837
      }
1838

1839
      drainKeyReferences();
1✔
1840
      drainValueReferences();
1✔
1841

1842
      expireEntries();
1✔
1843
      evictEntries();
1✔
1844

1845
      climb();
1✔
1846
    } finally {
1847
      if ((drainStatusOpaque() != PROCESSING_TO_IDLE)
1✔
1848
          || !casDrainStatus(PROCESSING_TO_IDLE, IDLE)) {
1✔
1849
        setDrainStatusOpaque(REQUIRED);
1✔
1850
      }
1851
    }
1852
  }
1✔
1853

1854
  /** Drains the weak key references queue. */
1855
  @GuardedBy("evictionLock")
1856
  void drainKeyReferences() {
1857
    if (!collectKeys()) {
1✔
1858
      return;
1✔
1859
    }
1860
    @Var Reference<? extends K> keyRef;
1861
    while ((keyRef = keyReferenceQueue().poll()) != null) {
1✔
1862
      Node<K, V> node = data.get(keyRef);
1✔
1863
      if (node != null) {
1✔
1864
        evictEntry(node, RemovalCause.COLLECTED, 0L);
1✔
1865
      }
1866
    }
1✔
1867
  }
1✔
1868

1869
  /** Drains the weak / soft value references queue. */
1870
  @GuardedBy("evictionLock")
1871
  void drainValueReferences() {
1872
    if (!collectValues()) {
1✔
1873
      return;
1✔
1874
    }
1875
    @Var Reference<? extends V> valueRef;
1876
    while ((valueRef = valueReferenceQueue().poll()) != null) {
1✔
1877
      @SuppressWarnings("unchecked")
1878
      var ref = (InternalReference<V>) valueRef;
1✔
1879
      Node<K, V> node = data.get(ref.getKeyReference());
1✔
1880
      if ((node != null) && (valueRef == node.getValueReference())) {
1✔
1881
        evictEntry(node, RemovalCause.COLLECTED, 0L);
1✔
1882
      }
1883
    }
1✔
1884
  }
1✔
1885

1886
  /** Drains the read buffer. */
1887
  @GuardedBy("evictionLock")
1888
  void drainReadBuffer() {
1889
    if (!skipReadBuffer()) {
1✔
1890
      readBuffer.drainTo(accessPolicy);
1✔
1891
    }
1892
  }
1✔
1893

1894
  /** Updates the node's location in the page replacement policy. */
1895
  @GuardedBy("evictionLock")
1896
  void onAccess(Node<K, V> node) {
1897
    if (evicts()) {
1✔
1898
      var keyRef = node.getKeyReferenceOrNull();
1✔
1899
      if ((keyRef == null) || !node.isAlive()) {
1✔
1900
        return;
1✔
1901
      }
1902
      frequencySketch().increment(keyRef);
1✔
1903
      if (node.inWindow()) {
1✔
1904
        reorder(accessOrderWindowDeque(), node);
1✔
1905
      } else if (node.inMainProbation()) {
1✔
1906
        reorderProbation(node);
1✔
1907
      } else {
1908
        reorder(accessOrderProtectedDeque(), node);
1✔
1909
      }
1910
      setHitsInSample(hitsInSample() + 1);
1✔
1911
    } else if (expiresAfterAccess()) {
1✔
1912
      reorder(accessOrderWindowDeque(), node);
1✔
1913
    }
1914
    if (expiresVariable()) {
1✔
1915
      timerWheel().reschedule(node);
1✔
1916
    }
1917
  }
1✔
1918

1919
  /** Promote the node from probation to protected on an access. */
1920
  @GuardedBy("evictionLock")
1921
  void reorderProbation(Node<K, V> node) {
1922
    if (!accessOrderProbationDeque().contains(node)) {
1✔
1923
      // Ignore stale accesses for an entry that is no longer present
1924
      return;
1✔
1925
    } else if (node.getPolicyWeight() > mainProtectedMaximum()) {
1✔
1926
      reorder(accessOrderProbationDeque(), node);
1✔
1927
      return;
1✔
1928
    }
1929

1930
    // If the protected space exceeds its maximum, the LRU items are demoted to the probation space.
1931
    // This is deferred to the adaption phase at the end of the maintenance cycle.
1932
    setMainProtectedWeightedSize(mainProtectedWeightedSize() + node.getPolicyWeight());
1✔
1933
    accessOrderProbationDeque().remove(node);
1✔
1934
    accessOrderProtectedDeque().offerLast(node);
1✔
1935
    node.makeMainProtected();
1✔
1936
  }
1✔
1937

1938
  /** Updates the node's location in the policy's deque. */
1939
  static <K, V> void reorder(LinkedDeque<Node<K, V>> deque, Node<K, V> node) {
1940
    // An entry may be scheduled for reordering despite having been removed. This can occur when the
1941
    // entry was concurrently read while a writer was removing it. If the entry is no longer linked
1942
    // then it does not need to be processed.
1943
    if (deque.contains(node)) {
1✔
1944
      deque.moveToBack(node);
1✔
1945
    }
1946
  }
1✔
1947

1948
  /** Drains the write buffer. */
1949
  @GuardedBy("evictionLock")
1950
  void drainWriteBuffer() {
1951
    for (int i = 0; i <= WRITE_BUFFER_MAX; i++) {
1✔
1952
      Runnable task = writeBuffer.poll();
1✔
1953
      if (task == null) {
1✔
1954
        return;
1✔
1955
      }
1956
      task.run();
1✔
1957
    }
1958
    setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1✔
1959
  }
1✔
1960

1961
  /**
1962
   * Atomically transitions the node to the <code>dead</code> state and decrements the
1963
   * <code>weightedSize</code>.
1964
   *
1965
   * @param node the entry in the page replacement policy
1966
   */
1967
  @GuardedBy("evictionLock")
1968
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
1969
  void makeDead(Node<K, V> node) {
1970
    synchronized (node) {
1✔
1971
      if (node.isDead()) {
1✔
1972
        return;
1✔
1973
      }
1974
      if (evicts()) {
1✔
1975
        // The node's policy weight may be out of sync due to a pending update waiting to be
1976
        // processed. At this point the node's weight is finalized, so the weight can be safely
1977
        // taken from the node's perspective and the sizes will be adjusted correctly.
1978
        if (node.inWindow()) {
1✔
1979
          setWindowWeightedSize(windowWeightedSize() - node.getWeight());
1✔
1980
        } else if (node.inMainProtected()) {
1✔
1981
          setMainProtectedWeightedSize(mainProtectedWeightedSize() - node.getWeight());
1✔
1982
        }
1983
        setWeightedSize(weightedSize() - node.getWeight());
1✔
1984
      }
1985
      node.die();
1✔
1986
    }
1✔
1987
  }
1✔
1988

1989
  /** Adds the node to the page replacement policy. */
1990
  final class AddTask implements Runnable {
1991
    final Node<K, V> node;
1992
    final int weight;
1993

1994
    AddTask(Node<K, V> node, int weight) {
1✔
1995
      this.weight = weight;
1✔
1996
      this.node = node;
1✔
1997
    }
1✔
1998

1999
    @Override
2000
    @GuardedBy("evictionLock")
2001
    public void run() {
2002
      if (evicts()) {
1✔
2003
        setWeightedSize(weightedSize() + weight);
1✔
2004
        setWindowWeightedSize(windowWeightedSize() + weight);
1✔
2005
        node.setPolicyWeight(node.getPolicyWeight() + weight);
1✔
2006

2007
        long maximum = maximum();
1✔
2008
        if (weightedSize() >= (maximum >>> 1)) {
1✔
2009
          if (weightedSize() > MAXIMUM_CAPACITY) {
1✔
2010
            evictEntries();
1✔
2011
          } else {
2012
            // Lazily initialize when close to the maximum
2013
            long capacity = isWeighted() ? data.mappingCount() : maximum;
1✔
2014
            frequencySketch().ensureCapacity(capacity);
1✔
2015
          }
2016
        }
2017

2018
        setMissesInSample(missesInSample() + 1);
1✔
2019
      }
2020

2021
      // ignore out-of-order write operations
2022
      boolean isAlive;
2023
      synchronized (node) {
1✔
2024
        isAlive = node.isAlive();
1✔
2025
      }
1✔
2026
      if (isAlive) {
1✔
2027
        if (expiresAfterWrite()) {
1✔
2028
          writeOrderDeque().offerLast(node);
1✔
2029
        }
2030
        if (expiresVariable()) {
1✔
2031
          timerWheel().schedule(node);
1✔
2032
        }
2033
        if (evicts()) {
1✔
2034
          var keyRef = node.getKeyReferenceOrNull();
1✔
2035
          if ((keyRef != null) && node.isAlive()) {
1✔
2036
            frequencySketch().increment(keyRef);
1✔
2037
          }
2038
          if (weight > maximum()) {
1✔
2039
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1✔
2040
          } else if (weight > windowMaximum()) {
1✔
2041
            accessOrderWindowDeque().offerFirst(node);
1✔
2042
          } else {
2043
            accessOrderWindowDeque().offerLast(node);
1✔
2044
          }
2045
        } else if (expiresAfterAccess()) {
1✔
2046
          accessOrderWindowDeque().offerLast(node);
1✔
2047
        }
2048
      }
2049
    }
1✔
2050
  }
2051

2052
  /** Removes a node from the page replacement policy. */
2053
  final class RemovalTask implements Runnable {
2054
    final Node<K, V> node;
2055

2056
    RemovalTask(Node<K, V> node) {
1✔
2057
      this.node = node;
1✔
2058
    }
1✔
2059

2060
    @Override
2061
    @GuardedBy("evictionLock")
2062
    public void run() {
2063
      // add may not have been processed yet
2064
      if (node.inWindow() && (evicts() || expiresAfterAccess())) {
1✔
2065
        accessOrderWindowDeque().remove(node);
1✔
2066
      } else if (evicts()) {
1✔
2067
        if (node.inMainProbation()) {
1✔
2068
          accessOrderProbationDeque().remove(node);
1✔
2069
        } else {
2070
          accessOrderProtectedDeque().remove(node);
1✔
2071
        }
2072
      }
2073
      if (expiresAfterWrite()) {
1✔
2074
        writeOrderDeque().remove(node);
1✔
2075
      } else if (expiresVariable()) {
1✔
2076
        timerWheel().deschedule(node);
1✔
2077
      }
2078
      makeDead(node);
1✔
2079
    }
1✔
2080
  }
2081

2082
  /** Updates the weighted size. */
2083
  final class UpdateTask implements Runnable {
2084
    final int weightDifference;
2085
    final Node<K, V> node;
2086

2087
    public UpdateTask(Node<K, V> node, int weightDifference) {
1✔
2088
      this.weightDifference = weightDifference;
1✔
2089
      this.node = node;
1✔
2090
    }
1✔
2091

2092
    @Override
2093
    @GuardedBy("evictionLock")
2094
    public void run() {
2095
      if (expiresAfterWrite()) {
1✔
2096
        reorder(writeOrderDeque(), node);
1✔
2097
      } else if (expiresVariable()) {
1✔
2098
        timerWheel().reschedule(node);
1✔
2099
      }
2100
      if (evicts()) {
1✔
2101
        int oldWeightedSize = node.getPolicyWeight();
1✔
2102
        node.setPolicyWeight(oldWeightedSize + weightDifference);
1✔
2103
        if (node.inWindow()) {
1✔
2104
          setWindowWeightedSize(windowWeightedSize() + weightDifference);
1✔
2105
          if (node.getPolicyWeight() > maximum()) {
1✔
2106
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1✔
2107
          } else if (node.getPolicyWeight() <= windowMaximum()) {
1✔
2108
            onAccess(node);
1✔
2109
          } else if (accessOrderWindowDeque().contains(node)) {
1✔
2110
            accessOrderWindowDeque().moveToFront(node);
1✔
2111
          }
2112
        } else if (node.inMainProbation()) {
1✔
2113
            if (node.getPolicyWeight() <= maximum()) {
1✔
2114
              onAccess(node);
1✔
2115
            } else {
2116
              evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1✔
2117
            }
2118
        } else {
2119
          setMainProtectedWeightedSize(mainProtectedWeightedSize() + weightDifference);
1✔
2120
          if (node.getPolicyWeight() <= maximum()) {
1✔
2121
            onAccess(node);
1✔
2122
          } else {
2123
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1✔
2124
          }
2125
        }
2126

2127
        setWeightedSize(weightedSize() + weightDifference);
1✔
2128
        if (weightedSize() > MAXIMUM_CAPACITY) {
1✔
2129
          evictEntries();
1✔
2130
        }
2131
      } else if (expiresAfterAccess()) {
1✔
2132
        onAccess(node);
1✔
2133
      }
2134
    }
1✔
2135
  }
2136

2137
  /* --------------- Concurrent Map Support --------------- */
2138

2139
  @Override
2140
  public boolean isEmpty() {
2141
    return data.isEmpty();
1✔
2142
  }
2143

2144
  @Override
2145
  public int size() {
2146
    return data.size();
1✔
2147
  }
2148

2149
  @Override
2150
  public long estimatedSize() {
2151
    return data.mappingCount();
1✔
2152
  }
2153

2154
  @Override
2155
  public void clear() {
2156
    Deque<Node<K, V>> entries;
2157
    evictionLock.lock();
1✔
2158
    try {
2159
      // Discard all pending reads
2160
      readBuffer.drainTo(e -> {});
1✔
2161

2162
      // Apply all pending writes
2163
      @Var Runnable task;
2164
      while ((task = writeBuffer.poll()) != null) {
1✔
2165
        task.run();
1✔
2166
      }
2167

2168
      // Cancel the scheduled cleanup
2169
      Pacer pacer = pacer();
1✔
2170
      if (pacer != null) {
1✔
2171
        pacer.cancel();
1✔
2172
      }
2173

2174
      // Discard all entries, falling back to one-by-one to avoid excessive lock hold times
2175
      long now = expirationTicker().read();
1✔
2176
      int threshold = (WRITE_BUFFER_MAX / 2);
1✔
2177
      entries = new ArrayDeque<>(data.values());
1✔
2178
      while (!entries.isEmpty() && (writeBuffer.size() < threshold)) {
1✔
2179
        removeNode(entries.pollFirst(), now);
1✔
2180
      }
2181
    } finally {
2182
      evictionLock.unlock();
1✔
2183
    }
2184

2185
    // Remove any stragglers if released early to more aggressively flush incoming writes
2186
    @Var boolean cleanUp = false;
1✔
2187
    for (var node : entries) {
1✔
2188
      @Nullable K key = node.getKey();
1✔
2189
      if (key == null) {
1✔
2190
        cleanUp = true;
1✔
2191
      } else {
2192
        remove(key);
1✔
2193
      }
2194
    }
1✔
2195
    if (collectKeys() && cleanUp) {
1✔
2196
      cleanUp();
1✔
2197
    } else if (entries.isEmpty()) {
1✔
2198
      rescheduleCleanUpIfIncomplete();
1✔
2199
    }
2200
  }
1✔
2201

2202
  @GuardedBy("evictionLock")
2203
  @SuppressWarnings({"GuardedByChecker", "SynchronizationOnLocalVariableOrMethodParameter"})
2204
  void removeNode(Node<K, V> node, long now) {
2205
    K key = node.getKey();
1✔
2206
    var ctx = new EvictContext<V>();
1✔
2207
    var keyReference = node.getKeyReference();
1✔
2208

2209
    data.computeIfPresent(keyReference, (k, n) -> {
1✔
2210
      if (n != node) {
1✔
2211
        return n;
1✔
2212
      }
2213
      synchronized (node) {
1✔
2214
        ctx.value = node.getValue();
1✔
2215
        ctx.oldWeight = node.getWeight();
1✔
2216

2217
        if ((key == null) || (ctx.value == null)) {
1✔
2218
          ctx.cause = RemovalCause.COLLECTED;
1✔
2219
        } else if (hasExpired(node, now, ctx.value)) {
1✔
2220
          ctx.cause = RemovalCause.EXPIRED;
1✔
2221
        } else {
2222
          ctx.cause = RemovalCause.EXPLICIT;
1✔
2223
        }
2224

2225
        if (ctx.cause.wasEvicted()) {
1✔
2226
          notifyEviction(key, ctx.value, ctx.cause);
1✔
2227
        }
2228

2229
        discardRefresh(node.getKeyReference());
1✔
2230
        node.retire();
1✔
2231
        return null;
1✔
2232
      }
2233
    });
2234

2235
    if (node.inWindow() && (evicts() || expiresAfterAccess())) {
1✔
2236
      accessOrderWindowDeque().remove(node);
1✔
2237
    } else if (evicts()) {
1✔
2238
      if (node.inMainProbation()) {
1✔
2239
        accessOrderProbationDeque().remove(node);
1✔
2240
      } else {
2241
        accessOrderProtectedDeque().remove(node);
1✔
2242
      }
2243
    }
2244
    if (expiresAfterWrite()) {
1✔
2245
      writeOrderDeque().remove(node);
1✔
2246
    } else if (expiresVariable()) {
1✔
2247
      timerWheel().deschedule(node);
1✔
2248
    }
2249

2250
    synchronized (node) {
1✔
2251
      logIfAlive(node);
1✔
2252
      makeDead(node);
1✔
2253
    }
1✔
2254

2255
    if (ctx.cause != null) {
1✔
2256
      if (ctx.cause.wasEvicted()) {
1✔
2257
        statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1✔
2258
      }
2259
      notifyRemoval(key, ctx.value, ctx.cause);
1✔
2260
    }
2261
  }
1✔
2262

2263
  @Override
2264
  public boolean containsKey(Object key) {
2265
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
2266
    if (node == null) {
1✔
2267
      return false;
1✔
2268
    }
2269
    V value = node.getValue();
1✔
2270
    if ((value == null) || hasExpired(node, expirationTicker().read(), value)) {
1✔
2271
      scheduleDrainBuffers();
1✔
2272
      return false;
1✔
2273
    }
2274
    return true;
1✔
2275
  }
2276

2277
  @Override
2278
  public boolean containsValue(Object value) {
2279
    requireNonNull(value);
1✔
2280

2281
    long now = expirationTicker().read();
1✔
2282
    for (Node<K, V> node : data.values()) {
1✔
2283
      V nodeValue = node.getValue();
1✔
2284
      if ((node.getKey() == null) || (nodeValue == null) || hasExpired(node, now, nodeValue)) {
1✔
2285
        scheduleDrainBuffers();
1✔
2286
      } else if (node.isAlive() && node.containsValue(value)) {
1✔
2287
        return true;
1✔
2288
      }
2289
    }
1✔
2290
    return false;
1✔
2291
  }
2292

2293
  @Override
2294
  public @Nullable V get(Object key) {
2295
    return getIfPresent(key, /* recordStats= */ false);
1✔
2296
  }
2297

2298
  @Override
2299
  public @Nullable V getIfPresent(Object key, boolean recordStats) {
2300
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
2301
    if (node == null) {
1✔
2302
      if (recordStats) {
1✔
2303
        statsCounter().recordMisses(1);
1✔
2304
      }
2305
      if (drainStatusOpaque() == REQUIRED) {
1✔
2306
        scheduleDrainBuffers();
1✔
2307
      }
2308
      return null;
1✔
2309
    }
2310

2311
    V value = node.getValue();
1✔
2312
    long now = expirationTicker().read();
1✔
2313
    if ((value == null) || hasExpired(node, now, value)) {
1✔
2314
      if (recordStats) {
1✔
2315
        statsCounter().recordMisses(1);
1✔
2316
      }
2317
      scheduleDrainBuffers();
1✔
2318
      return null;
1✔
2319
    }
2320

2321
    if (!isComputingAsync(value)) {
1✔
2322
      @SuppressWarnings("unchecked")
2323
      var castedKey = (K) key;
1✔
2324
      setAccessTime(node, now);
1✔
2325
      tryExpireAfterRead(node, castedKey, value, expiry(), now);
1✔
2326
    }
2327
    V refreshed = afterRead(node, now, recordStats);
1✔
2328
    return (refreshed == null) ? value : refreshed;
1✔
2329
  }
2330

2331
  @Override
2332
  public @Nullable V getIfPresentQuietly(Object key) {
2333
    V value;
2334
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
2335
    if ((node == null) || ((value = node.getValue()) == null)
1✔
2336
        || hasExpired(node, expirationTicker().read(), value)) {
1✔
2337
      return null;
1✔
2338
    }
2339
    return value;
1✔
2340
  }
2341

2342
  /**
2343
   * Returns the key associated with the mapping in this cache, or {@code null} if there is none.
2344
   *
2345
   * @param key the key whose canonical instance is to be returned
2346
   * @return the key used by the mapping, or {@code null} if this cache does not contain a mapping
2347
   *         for the key
2348
   * @throws NullPointerException if the specified key is null
2349
   */
2350
  public @Nullable K getKey(K key) {
2351
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
2352
    if (node == null) {
1✔
2353
      if (drainStatusOpaque() == REQUIRED) {
1✔
2354
        scheduleDrainBuffers();
1✔
2355
      }
2356
      return null;
1✔
2357
    }
2358
    afterRead(node, /* now= */ 0L, /* recordHit= */ false);
1✔
2359
    return node.getKey();
1✔
2360
  }
2361

2362
  @Override
2363
  public Map<K, V> getAllPresent(Iterable<? extends K> keys) {
2364
    var result = new LinkedHashMap<K, @Nullable V>(calculateHashMapCapacity(keys));
1✔
2365
    for (K key : keys) {
1✔
2366
      result.put(key, null);
1✔
2367
    }
1✔
2368

2369
    @Var boolean drain = false;
1✔
2370
    int uniqueKeys = result.size();
1✔
2371
    long now = expirationTicker().read();
1✔
2372
    for (var iter = result.entrySet().iterator(); iter.hasNext();) {
1✔
2373
      V value;
2374
      var entry = iter.next();
1✔
2375
      Node<K, V> node = data.get(nodeFactory.newLookupKey(entry.getKey()));
1✔
2376
      if (node == null) {
1✔
2377
        iter.remove();
1✔
2378
      } else if (((value = node.getValue()) == null) || hasExpired(node, now, value)) {
1✔
2379
        iter.remove();
1✔
2380
        drain = true;
1✔
2381
      } else {
2382
        setAccessTime(node, now);
1✔
2383
        tryExpireAfterRead(node, entry.getKey(), value, expiry(), now);
1✔
2384
        V refreshed = afterRead(node, now, /* recordHit= */ false);
1✔
2385
        entry.setValue((refreshed == null) ? value : refreshed);
1✔
2386
      }
2387
    }
1✔
2388
    if (drain) {
1✔
2389
      scheduleDrainBuffers();
1✔
2390
    }
2391
    statsCounter().recordHits(result.size());
1✔
2392
    statsCounter().recordMisses(uniqueKeys - result.size());
1✔
2393

2394
    @SuppressWarnings("NullableProblems")
2395
    Map<K, V> unmodifiable = Collections.unmodifiableMap(result);
1✔
2396
    return unmodifiable;
1✔
2397
  }
2398

2399
  @Override
2400
  public void putAll(Map<? extends K, ? extends V> map) {
2401
    map.forEach(this::put);
1✔
2402
  }
1✔
2403

2404
  @Override
2405
  public @Nullable V put(K key, V value) {
2406
    return put(key, value, expiry(), /* onlyIfAbsent= */ false);
1✔
2407
  }
2408

2409
  @Override
2410
  public @Nullable V putIfAbsent(K key, V value) {
2411
    return put(key, value, expiry(), /* onlyIfAbsent= */ true);
1✔
2412
  }
2413

2414
  /**
2415
   * Adds a node to the policy and the data store. If an existing node is found, then its value is
2416
   * updated if allowed.
2417
   *
2418
   * @param key key with which the specified value is to be associated
2419
   * @param value value to be associated with the specified key
2420
   * @param expiry the calculator for the write expiration time
2421
   * @param onlyIfAbsent a write is performed only if the key is not already associated with a value
2422
   * @return the prior value in or null if no mapping was found
2423
   */
2424
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2425
  @Nullable V put(K key, V value, Expiry<K, V> expiry, boolean onlyIfAbsent) {
2426
    requireNonNull(key);
1✔
2427
    requireNonNull(value);
1✔
2428

2429
    @Var int newWeight = -1;
1✔
2430
    @Var Object keyRef = null;
1✔
2431
    @Var Node<K, V> node = null;
1✔
2432
    Object lookupKey = nodeFactory.newLookupKey(key);
1✔
2433
    for (int attempts = 1; ; attempts++) {
1✔
2434
      @Var Node<K, V> prior = data.get(lookupKey);
1✔
2435
      if (prior == null) {
1✔
2436
        if (node == null) {
1✔
2437
          if (newWeight < 0) {
1✔
2438
            newWeight = weigher.weigh(key, value);
1✔
2439
          }
2440
          long now = expirationTicker().read();
1✔
2441
          keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1✔
2442
          node = nodeFactory.newNode(keyRef, value, valueReferenceQueue(), newWeight, now);
1✔
2443
          long expirationTime = isComputingAsync(value) ? (now + ASYNC_EXPIRY) : now;
1✔
2444
          setVariableTime(node, expireAfterCreate(key, value, expiry, now));
1✔
2445
          setAccessTime(node, expirationTime);
1✔
2446
          setWriteTime(node, expirationTime);
1✔
2447
        }
2448
        var newNode = node;
1✔
2449
        prior = (cacheLoader == null)
1✔
2450
            ? data.putIfAbsent(keyRef, newNode)
1✔
2451
            : data.computeIfAbsent(keyRef, k -> {
1✔
2452
                discardRefresh(k);
1✔
2453
                return newNode;
1✔
2454
              });
2455
        if ((prior == null) || (prior == node)) {
1✔
2456
          afterWrite(new AddTask(node, newWeight));
1✔
2457
          return null;
1✔
2458
        } else if (onlyIfAbsent) {
1✔
2459
          // An optimistic fast path to avoid unnecessary locking
2460
          V currentValue = prior.getValue();
1✔
2461
          long now = expirationTicker().read();
1✔
2462
          if ((currentValue != null) && !hasExpired(prior, now, currentValue)) {
1✔
2463
            if (!isComputingAsync(currentValue)) {
1✔
2464
              tryExpireAfterRead(prior, key, currentValue, expiry, now);
1✔
2465
              setAccessTime(prior, now);
1✔
2466
            }
2467
            afterRead(prior, now, /* recordHit= */ false);
1✔
2468
            return currentValue;
1✔
2469
          }
2470
        }
2471
      } else if (onlyIfAbsent) {
1✔
2472
        // An optimistic fast path to avoid unnecessary locking
2473
        V currentValue = prior.getValue();
1✔
2474
        long now = expirationTicker().read();
1✔
2475
        if ((currentValue != null) && !hasExpired(prior, now, currentValue)) {
1✔
2476
          if (!isComputingAsync(currentValue)) {
1✔
2477
            tryExpireAfterRead(prior, key, currentValue, expiry, now);
1✔
2478
            setAccessTime(prior, now);
1✔
2479
          }
2480
          afterRead(prior, now, /* recordHit= */ false);
1✔
2481
          return currentValue;
1✔
2482
        }
2483
      }
2484

2485
      // A read may race with the entry's removal, so that after the entry is acquired it may no
2486
      // longer be usable. A retry will reread from the map and either find an absent mapping, a
2487
      // new entry, or a stale entry.
2488
      if (!prior.isAlive()) {
1✔
2489
        // A reread of the stale entry may occur if the state transition occurred but the map
2490
        // removal was delayed by a context switch, so that this thread spin waits until resolved.
2491
        if ((attempts & MAX_PUT_SPIN_WAIT_ATTEMPTS) != 0) {
1✔
2492
          Thread.onSpinWait();
1✔
2493
          continue;
1✔
2494
        }
2495

2496
        // If the spin wait attempts are exhausted then fallback to a map computation in order to
2497
        // deschedule this thread until the entry's removal completes. If the key was modified
2498
        // while in the map so that its equals or hashCode changed then the contents may be
2499
        // corrupted, where the cache holds an evicted (dead) entry that could not be removed.
2500
        // That is a violation of the Map contract, so we check that the mapping is in the "alive"
2501
        // state while in the computation.
2502
        data.computeIfPresent(lookupKey, (k, n) -> {
1✔
2503
          requireIsAlive(key, n);
1✔
2504
          return n;
1✔
2505
        });
2506
        continue;
1✔
2507
      }
2508

2509
      long now;
2510
      V oldValue;
2511
      long varTime;
2512
      int oldWeight;
2513
      @Var boolean expired = false;
1✔
2514
      @Var boolean mayUpdate = true;
1✔
2515
      @Var boolean exceedsTolerance = false;
1✔
2516
      if (newWeight < 0) {
1✔
2517
        newWeight = weigher.weigh(key, value);
1✔
2518
      }
2519
      synchronized (prior) {
1✔
2520
        if (!prior.isAlive()) {
1✔
2521
          continue;
1✔
2522
        }
2523
        oldValue = prior.getValue();
1✔
2524
        oldWeight = prior.getWeight();
1✔
2525
        now = expirationTicker().read();
1✔
2526
        if (oldValue == null) {
1✔
2527
          varTime = expireAfterCreate(key, value, expiry, now);
1✔
2528
          notifyEviction(key, null, RemovalCause.COLLECTED);
1✔
2529
        } else if (hasExpired(prior, now, oldValue)) {
1✔
2530
          expired = true;
1✔
2531
          varTime = expireAfterCreate(key, value, expiry, now);
1✔
2532
          notifyEviction(key, oldValue, RemovalCause.EXPIRED);
1✔
2533
        } else if (onlyIfAbsent) {
1✔
2534
          mayUpdate = false;
1✔
2535
          varTime = expireAfterRead(prior, key, oldValue, expiry, now);
1✔
2536
        } else {
2537
          varTime = expireAfterUpdate(prior, key, value, expiry, now);
1✔
2538
        }
2539

2540
        long expirationTime = isComputingAsync(mayUpdate ? value : oldValue)
1✔
2541
            ? (now + ASYNC_EXPIRY)
1✔
2542
            : now;
1✔
2543
        if (mayUpdate) {
1✔
2544
          exceedsTolerance = exceedsWriteTimeTolerance(prior, varTime, expirationTime);
1✔
2545
          if (expired || exceedsTolerance) {
1✔
2546
            setWriteTime(prior, expirationTime);
1✔
2547
          }
2548

2549
          prior.setValue(value, valueReferenceQueue());
1✔
2550
          prior.setWeight(newWeight);
1✔
2551

2552
          discardRefresh(prior.getKeyReference());
1✔
2553
        }
2554

2555
        setVariableTime(prior, varTime);
1✔
2556
        setAccessTime(prior, expirationTime);
1✔
2557
      }
1✔
2558

2559
      if (expired) {
1✔
2560
        statsCounter().recordEviction(oldWeight, RemovalCause.EXPIRED);
1✔
2561
        notifyRemoval(key, oldValue, RemovalCause.EXPIRED);
1✔
2562
      } else if (oldValue == null) {
1✔
2563
        statsCounter().recordEviction(oldWeight, RemovalCause.COLLECTED);
1✔
2564
        notifyRemoval(key, /* value= */ null, RemovalCause.COLLECTED);
1✔
2565
      } else if (mayUpdate) {
1✔
2566
        notifyOnReplace(key, oldValue, value);
1✔
2567
      }
2568

2569
      int weightedDifference = mayUpdate ? (newWeight - oldWeight) : 0;
1✔
2570
      if ((oldValue == null) || (weightedDifference != 0) || expired) {
1✔
2571
        afterWrite(new UpdateTask(prior, weightedDifference));
1✔
2572
      } else if (!onlyIfAbsent && exceedsTolerance) {
1✔
2573
        afterWrite(new UpdateTask(prior, weightedDifference));
1✔
2574
      } else {
2575
        afterRead(prior, now, /* recordHit= */ false);
1✔
2576
      }
2577

2578
      return expired ? null : oldValue;
1✔
2579
    }
2580
  }
2581

2582
  @Override
2583
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2584
  public @Nullable V remove(Object key) {
2585
    var ctx = new RemoveContext<K, V>();
1✔
2586
    Object lookupKey = nodeFactory.newLookupKey(key);
1✔
2587
    data.computeIfPresent(lookupKey, (k, n) -> {
1✔
2588
      synchronized (n) {
1✔
2589
        requireIsAlive(key, n);
1✔
2590
        ctx.oldKey = n.getKey();
1✔
2591
        ctx.oldValue = n.getValue();
1✔
2592
        ctx.oldWeight = n.getWeight();
1✔
2593
        RemovalCause actualCause;
2594
        if ((ctx.oldKey == null) || (ctx.oldValue == null)) {
1✔
2595
          actualCause = RemovalCause.COLLECTED;
1✔
2596
        } else if (hasExpired(n, expirationTicker().read(), ctx.oldValue)) {
1✔
2597
          actualCause = RemovalCause.EXPIRED;
1✔
2598
        } else {
2599
          actualCause = RemovalCause.EXPLICIT;
1✔
2600
        }
2601
        if (actualCause.wasEvicted()) {
1✔
2602
          notifyEviction(ctx.oldKey, ctx.oldValue, actualCause);
1✔
2603
        }
2604
        ctx.cause = actualCause;
1✔
2605
        discardRefresh(k);
1✔
2606
        ctx.node = n;
1✔
2607
        n.retire();
1✔
2608
        return null;
1✔
2609
      }
2610
    });
2611

2612
    if (ctx.cause != null) {
1✔
2613
      afterWrite(new RemovalTask(requireNonNull(ctx.node)));
1✔
2614
      if (ctx.cause.wasEvicted()) {
1✔
2615
        statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1✔
2616
      }
2617
      notifyRemoval(ctx.oldKey, ctx.oldValue, ctx.cause);
1✔
2618
    }
2619
    return (ctx.cause == RemovalCause.EXPLICIT) ? ctx.oldValue : null;
1✔
2620
  }
2621

2622
  @Override
2623
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2624
  public boolean remove(Object key, @Nullable Object value) {
2625
    requireNonNull(key);
1✔
2626
    if (value == null) {
1✔
2627
      return false;
1✔
2628
    }
2629

2630
    var ctx = new RemoveContext<K, V>();
1✔
2631
    Object lookupKey = nodeFactory.newLookupKey(key);
1✔
2632
    data.computeIfPresent(lookupKey, (kR, node) -> {
1✔
2633
      synchronized (node) {
1✔
2634
        requireIsAlive(key, node);
1✔
2635
        ctx.oldKey = node.getKey();
1✔
2636
        ctx.oldValue = node.getValue();
1✔
2637
        ctx.oldWeight = node.getWeight();
1✔
2638
        if ((ctx.oldKey == null) || (ctx.oldValue == null)) {
1✔
2639
          ctx.cause = RemovalCause.COLLECTED;
1✔
2640
        } else if (hasExpired(node, expirationTicker().read(), ctx.oldValue)) {
1✔
2641
          ctx.cause = RemovalCause.EXPIRED;
1✔
2642
        } else if (node.containsValue(value)) {
1✔
2643
          ctx.cause = RemovalCause.EXPLICIT;
1✔
2644
        } else {
2645
          return node;
1✔
2646
        }
2647
        if (ctx.cause.wasEvicted()) {
1✔
2648
          notifyEviction(ctx.oldKey, ctx.oldValue, ctx.cause);
1✔
2649
        }
2650
        discardRefresh(kR);
1✔
2651
        ctx.node = node;
1✔
2652
        node.retire();
1✔
2653
        return null;
1✔
2654
      }
2655
    });
2656

2657
    if (ctx.node == null) {
1✔
2658
      return false;
1✔
2659
    }
2660
    var removeCause = requireNonNull(ctx.cause);
1✔
2661
    afterWrite(new RemovalTask(ctx.node));
1✔
2662
    if (removeCause.wasEvicted()) {
1✔
2663
      statsCounter().recordEviction(ctx.oldWeight, removeCause);
1✔
2664
    }
2665
    notifyRemoval(ctx.oldKey, ctx.oldValue, removeCause);
1✔
2666

2667
    return (removeCause == RemovalCause.EXPLICIT);
1✔
2668
  }
2669

2670
  @Override
2671
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2672
  public @Nullable V replace(K key, V value) {
2673
    requireNonNull(key);
1✔
2674
    requireNonNull(value);
1✔
2675
    var ctx = new ReplaceContext<K, V>();
1✔
2676
    int weight = weigher.weigh(key, value);
1✔
2677
    Node<K, V> node = data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> {
1✔
2678
      synchronized (n) {
1✔
2679
        requireIsAlive(key, n);
1✔
2680
        ctx.nodeKey = n.getKey();
1✔
2681
        ctx.oldValue = n.getValue();
1✔
2682
        ctx.oldWeight = n.getWeight();
1✔
2683
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)
1✔
2684
            || hasExpired(n, ctx.now = expirationTicker().read(), ctx.oldValue)) {
1✔
2685
          ctx.oldValue = null;
1✔
2686
          return n;
1✔
2687
        }
2688

2689
        long varTime = expireAfterUpdate(n, key, value, expiry(), ctx.now);
1✔
2690
        n.setValue(value, valueReferenceQueue());
1✔
2691
        n.setWeight(weight);
1✔
2692

2693
        long expirationTime = isComputingAsync(value) ? (ctx.now + ASYNC_EXPIRY) : ctx.now;
1✔
2694
        ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1✔
2695
        if (ctx.exceedsTolerance) {
1✔
2696
          setWriteTime(n, expirationTime);
1✔
2697
        }
2698
        setAccessTime(n, expirationTime);
1✔
2699
        setVariableTime(n, varTime);
1✔
2700
        discardRefresh(k);
1✔
2701
        return n;
1✔
2702
      }
2703
    });
2704

2705
    if ((node == null) || (ctx.nodeKey == null) || (ctx.oldValue == null)) {
1✔
2706
      if (node != null) {
1✔
2707
        scheduleDrainBuffers();
1✔
2708
      }
2709
      return null;
1✔
2710
    }
2711

2712
    int weightedDifference = (weight - ctx.oldWeight);
1✔
2713
    if (ctx.exceedsTolerance || (weightedDifference != 0)) {
1✔
2714
      afterWrite(new UpdateTask(node, weightedDifference));
1✔
2715
    } else {
2716
      afterRead(node, ctx.now, /* recordHit= */ false);
1✔
2717
    }
2718

2719
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, value);
1✔
2720
    return ctx.oldValue;
1✔
2721
  }
2722

2723
  @Override
2724
  public boolean replace(K key, V oldValue, V newValue) {
2725
    return replace(key, oldValue, newValue, /* shouldDiscardRefresh= */ true);
1✔
2726
  }
2727

2728
  @Override
2729
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2730
  public boolean replace(K key, V oldValue, V newValue, boolean shouldDiscardRefresh) {
2731
    requireNonNull(key);
1✔
2732
    requireNonNull(oldValue);
1✔
2733
    requireNonNull(newValue);
1✔
2734
    var ctx = new ReplaceContext<K, V>();
1✔
2735
    int weight = weigher.weigh(key, newValue);
1✔
2736
    Node<K, V> node = data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> {
1✔
2737
      synchronized (n) {
1✔
2738
        requireIsAlive(key, n);
1✔
2739
        ctx.nodeKey = n.getKey();
1✔
2740
        ctx.oldValue = n.getValue();
1✔
2741
        ctx.oldWeight = n.getWeight();
1✔
2742
        if ((ctx.nodeKey == null) || (ctx.oldValue == null) || !n.containsValue(oldValue)
1✔
2743
            || hasExpired(n, ctx.now = expirationTicker().read(), ctx.oldValue)) {
1✔
2744
          ctx.oldValue = null;
1✔
2745
          return n;
1✔
2746
        }
2747

2748
        long varTime = expireAfterUpdate(n, key, newValue, expiry(), ctx.now);
1✔
2749
        n.setValue(newValue, valueReferenceQueue());
1✔
2750
        n.setWeight(weight);
1✔
2751

2752
        long expirationTime = isComputingAsync(newValue) ? (ctx.now + ASYNC_EXPIRY) : ctx.now;
1✔
2753
        ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1✔
2754
        if (ctx.exceedsTolerance) {
1✔
2755
          setWriteTime(n, expirationTime);
1✔
2756
        }
2757
        setAccessTime(n, expirationTime);
1✔
2758
        setVariableTime(n, varTime);
1✔
2759

2760
        if (shouldDiscardRefresh) {
1✔
2761
          discardRefresh(k);
1✔
2762
        }
2763
      }
1✔
2764
      return n;
1✔
2765
    });
2766

2767
    if ((node == null) || (ctx.nodeKey == null) || (ctx.oldValue == null)) {
1✔
2768
      if (node != null) {
1✔
2769
        scheduleDrainBuffers();
1✔
2770
      }
2771
      return false;
1✔
2772
    }
2773

2774
    int weightedDifference = (weight - ctx.oldWeight);
1✔
2775
    if (ctx.exceedsTolerance || (weightedDifference != 0)) {
1✔
2776
      afterWrite(new UpdateTask(node, weightedDifference));
1✔
2777
    } else {
2778
      afterRead(node, ctx.now, /* recordHit= */ false);
1✔
2779
    }
2780

2781
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, newValue);
1✔
2782
    return true;
1✔
2783
  }
2784

2785
  @Override
2786
  public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
2787
    requireNonNull(function);
1✔
2788

2789
    BiFunction<K, V, V> remappingFunction = (key, oldValue) ->
1✔
2790
        requireNonNull(function.apply(key, oldValue));
1✔
2791
    for (K key : keySet()) {
1✔
2792
      Object lookupKey = nodeFactory.newLookupKey(key);
1✔
2793
      remap(key, lookupKey, remappingFunction, expiry(),
1✔
2794
          new ComputeContext<>(expirationTicker().read()), /* computeIfAbsent= */ false);
1✔
2795
    }
1✔
2796
  }
1✔
2797

2798
  @Override
2799
  public @Nullable V computeIfAbsent(K key,
2800
      @Var Function<? super K, ? extends @Nullable V> mappingFunction,
2801
      boolean recordStats, boolean recordLoad) {
2802
    requireNonNull(key);
1✔
2803
    requireNonNull(mappingFunction);
1✔
2804

2805
    // An optimistic fast path to avoid unnecessary locking
2806
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1✔
2807
    long now = expirationTicker().read();
1✔
2808
    if (node != null) {
1✔
2809
      V value = node.getValue();
1✔
2810
      if ((value != null) && !hasExpired(node, now, value)) {
1✔
2811
        if (!isComputingAsync(value)) {
1✔
2812
          tryExpireAfterRead(node, key, value, expiry(), now);
1✔
2813
          setAccessTime(node, now);
1✔
2814
        }
2815
        @Nullable V refreshed = afterRead(node, now, /* recordHit= */ recordStats);
1✔
2816
        return (refreshed == null) ? value : refreshed;
1✔
2817
      }
2818
    }
2819
    if (recordStats) {
1✔
2820
      mappingFunction = statsAware(mappingFunction, recordLoad);
1✔
2821
    }
2822
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1✔
2823
    return doComputeIfAbsent(key, keyRef, mappingFunction,
1✔
2824
        new ComputeContext<>(now), recordStats);
2825
  }
2826

2827
  /** Returns the current value from a computeIfAbsent invocation. */
2828
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2829
  @Nullable V doComputeIfAbsent(K key, Object keyRef,
2830
      Function<? super K, ? extends @Nullable V> mappingFunction,
2831
      ComputeContext<K, V> ctx, boolean recordStats) {
2832
    Node<K, V> node = data.compute(keyRef, (k, n) -> {
1✔
2833
      if (n == null) {
1✔
2834
        ctx.newValue = mappingFunction.apply(key);
1✔
2835
        if (ctx.newValue == null) {
1✔
2836
          discardRefresh(k);
1✔
2837
          return null;
1✔
2838
        }
2839
        ctx.now = expirationTicker().read();
1✔
2840
        ctx.newWeight = weigher.weigh(key, ctx.newValue);
1✔
2841
        var created = nodeFactory.newNode(k, ctx.newValue,
1✔
2842
            valueReferenceQueue(), ctx.newWeight, ctx.now);
1✔
2843
        long expirationTime = isComputingAsync(ctx.newValue)
1✔
2844
            ? ctx.now + ASYNC_EXPIRY
1✔
2845
            : ctx.now;
1✔
2846
        setVariableTime(created, expireAfterCreate(key, ctx.newValue, expiry(), ctx.now));
1✔
2847
        setAccessTime(created, expirationTime);
1✔
2848
        setWriteTime(created, expirationTime);
1✔
2849
        discardRefresh(k);
1✔
2850
        return created;
1✔
2851
      }
2852

2853
      synchronized (n) {
1✔
2854
        requireIsAlive(key, n);
1✔
2855
        ctx.nodeKey = n.getKey();
1✔
2856
        ctx.oldValue = n.getValue();
1✔
2857
        ctx.oldWeight = n.getWeight();
1✔
2858
        RemovalCause actualCause;
2859
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)) {
1✔
2860
          actualCause = RemovalCause.COLLECTED;
1✔
2861
        } else if (hasExpired(n, ctx.now = expirationTicker().read(), ctx.oldValue)) {
1✔
2862
          actualCause = RemovalCause.EXPIRED;
1✔
2863
        } else {
2864
          return n;
1✔
2865
        }
2866

2867
        ctx.cause = actualCause;
1✔
2868
        notifyEviction(ctx.nodeKey, ctx.oldValue, actualCause);
1✔
2869

2870
        try {
2871
          ctx.newValue = mappingFunction.apply(key);
1✔
2872
          if (ctx.newValue == null) {
1✔
2873
            discardRefresh(k);
1✔
2874
            ctx.removed = n;
1✔
2875
            n.retire();
1✔
2876
            return null;
1✔
2877
          }
2878
          ctx.now = expirationTicker().read();
1✔
2879
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1✔
2880
          long varTime = expireAfterCreate(key, ctx.newValue, expiry(), ctx.now);
1✔
2881

2882
          n.setValue(ctx.newValue, valueReferenceQueue());
1✔
2883
          n.setWeight(ctx.newWeight);
1✔
2884

2885
          long expirationTime = isComputingAsync(ctx.newValue)
1!
2886
              ? (ctx.now + ASYNC_EXPIRY) : ctx.now;
1✔
2887
          setAccessTime(n, expirationTime);
1✔
2888
          setWriteTime(n, expirationTime);
1✔
2889
          setVariableTime(n, varTime);
1✔
2890
          discardRefresh(k);
1✔
2891
          return n;
1✔
2892
        } catch (Throwable e) {
1✔
2893
          ctx.newValue = null;
1✔
2894
          discardRefresh(k);
1✔
2895
          ctx.exception = e;
1✔
2896
          ctx.removed = n;
1✔
2897
          n.retire();
1✔
2898
          return null;
1✔
2899
        }
2900
      }
2901
    });
2902

2903
    if (ctx.cause != null) {
1✔
2904
      statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1✔
2905
      notifyRemoval(ctx.nodeKey, ctx.oldValue, ctx.cause);
1✔
2906
    }
2907
    if (node == null) {
1✔
2908
      if (ctx.removed != null) {
1✔
2909
        afterWrite(new RemovalTask(ctx.removed));
1✔
2910
      }
2911
      if (ctx.exception != null) {
1✔
2912
        throw toUncheckedException(ctx.exception);
1✔
2913
      }
2914
      return null;
1✔
2915
    }
2916
    if ((ctx.oldValue != null) && (ctx.newValue == null)) {
1✔
2917
      if (!isComputingAsync(ctx.oldValue)) {
1✔
2918
        tryExpireAfterRead(node, key, ctx.oldValue, expiry(), ctx.now);
1✔
2919
        setAccessTime(node, ctx.now);
1✔
2920
      }
2921

2922
      @Nullable V refreshed = afterRead(node, ctx.now, /* recordHit= */ recordStats);
1✔
2923
      return (refreshed == null) ? ctx.oldValue : refreshed;
1✔
2924
    }
2925
    if ((ctx.oldValue == null) && (ctx.cause == null)) {
1✔
2926
      afterWrite(new AddTask(node, ctx.newWeight));
1✔
2927
    } else {
2928
      int weightedDifference = (ctx.newWeight - ctx.oldWeight);
1✔
2929
      afterWrite(new UpdateTask(node, weightedDifference));
1✔
2930
    }
2931

2932
    return ctx.newValue;
1✔
2933
  }
2934

2935
  @Override
2936
  public @Nullable V computeIfPresent(K key,
2937
      BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
2938
    requireNonNull(key);
1✔
2939
    requireNonNull(remappingFunction);
1✔
2940

2941
    // An optimistic fast path to avoid unnecessary locking
2942
    Object lookupKey = nodeFactory.newLookupKey(key);
1✔
2943
    @Nullable Node<K, V> node = data.get(lookupKey);
1✔
2944
    long now;
2945
    if (node == null) {
1✔
2946
      return null;
1✔
2947
    }
2948
    V value = node.getValue();
1✔
2949
    if ((value == null) || hasExpired(node, now = expirationTicker().read(), value)) {
1✔
2950
      scheduleDrainBuffers();
1✔
2951
      return null;
1✔
2952
    }
2953

2954
    BiFunction<? super K, ? super V, ? extends V> statsAwareRemappingFunction =
1✔
2955
        statsAware(remappingFunction, /* recordLoad= */ true, /* recordLoadFailure= */ true);
1✔
2956
    return remap(key, lookupKey, statsAwareRemappingFunction,
1✔
2957
        expiry(), new ComputeContext<>(now), /* computeIfAbsent= */ false);
1✔
2958
  }
2959

2960
  @Override
2961
  public @Nullable V compute(K key,
2962
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction,
2963
      @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad, boolean recordLoadFailure,
2964
      @Nullable RemapHints hints) {
2965
    requireNonNull(key);
1✔
2966
    requireNonNull(remappingFunction);
1✔
2967

2968
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1✔
2969
    BiFunction<? super K, ? super V, ? extends V> statsAwareRemappingFunction =
1✔
2970
        statsAware(remappingFunction, recordLoad, recordLoadFailure);
1✔
2971
    var ctx = new ComputeContext<K, V>(expirationTicker().read());
1✔
2972
    ctx.hints = hints;
1✔
2973
    return remap(key, keyRef, statsAwareRemappingFunction,
1✔
2974
        expiry, ctx, /* computeIfAbsent= */ true);
2975
  }
2976

2977
  @Override
2978
  public @Nullable V merge(K key, V value,
2979
      BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
2980
    requireNonNull(key);
1✔
2981
    requireNonNull(value);
1✔
2982
    requireNonNull(remappingFunction);
1✔
2983

2984
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1✔
2985
    BiFunction<? super V, ? super V, ? extends V> f = statsAware(remappingFunction);
1✔
2986
    BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> mergeFunction =
1✔
2987
        (k, oldValue) -> (oldValue == null) ? value : f.apply(oldValue, value);
1✔
2988
    return remap(key, keyRef, mergeFunction, expiry(),
1✔
2989
        new ComputeContext<>(expirationTicker().read()), /* computeIfAbsent= */ true);
1✔
2990
  }
2991

2992
  /**
2993
   * Attempts to compute a mapping for the specified key and its current mapped value (or
2994
   * {@code null} if there is no current mapping).
2995
   * <p>
2996
   * An entry that has expired or been reference collected is evicted and the computation continues
2997
   * as if the entry had not been present. This method does not pre-screen and does not wrap the
2998
   * remappingFunction to be statistics aware.
2999
   *
3000
   * @param key key with which the specified value is to be associated
3001
   * @param keyRef the key to associate with or a lookup only key if not {@code computeIfAbsent}
3002
   * @param remappingFunction the function to compute a value
3003
   * @param expiry the calculator for the expiration time
3004
   * @param ctx the mutable context for passing state to and from the {@link ConcurrentHashMap}
3005
   *        compute lambda, with {@link ComputeContext#now} set to the current ticker time
3006
   * @param computeIfAbsent if an absent entry can be computed
3007
   * @return the new value associated with the specified key, or null if none
3008
   */
3009
  @SuppressWarnings({"StatementWithEmptyBody", "SynchronizationOnLocalVariableOrMethodParameter"})
3010
  @Nullable V remap(K key, Object keyRef,
3011
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction,
3012
      @Nullable Expiry<? super K, ? super V> expiry,
3013
      ComputeContext<K, V> ctx, boolean computeIfAbsent) {
3014
    Node<K, V> node = data.compute(keyRef, (kr, n) -> {
1✔
3015
      if (n == null) {
1✔
3016
        if (!computeIfAbsent) {
1✔
3017
          return null;
1✔
3018
        }
3019
        ctx.newValue = remappingFunction.apply(key, null);
1✔
3020
        if (ctx.newValue == null) {
1✔
3021
          discardRefresh(kr);
1✔
3022
          return null;
1✔
3023
        }
3024
        try {
3025
          ctx.now = expirationTicker().read();
1✔
3026
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1✔
3027
          long varTime = expireAfterCreate(key, ctx.newValue, expiry, ctx.now);
1✔
3028
          var created = nodeFactory.newNode(keyRef, ctx.newValue,
1✔
3029
              valueReferenceQueue(), ctx.newWeight, ctx.now);
1✔
3030

3031
          long expirationTime = isComputingAsync(ctx.newValue)
1✔
3032
              ? ctx.now + ASYNC_EXPIRY
1✔
3033
              : ctx.now;
1✔
3034
          setAccessTime(created, expirationTime);
1✔
3035
          setWriteTime(created, expirationTime);
1✔
3036
          setVariableTime(created, varTime);
1✔
3037
          return created;
1✔
3038
        } finally {
3039
          discardRefresh(kr);
1✔
3040
        }
3041
      }
3042

3043
      synchronized (n) {
1✔
3044
        requireIsAlive(key, n);
1✔
3045
        ctx.nodeKey = n.getKey();
1✔
3046
        ctx.oldValue = n.getValue();
1✔
3047
        ctx.oldWeight = n.getWeight();
1✔
3048
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)) {
1✔
3049
          ctx.cause = RemovalCause.COLLECTED;
1✔
3050
        } else if (hasExpired(n, expirationTicker().read(), ctx.oldValue)) {
1✔
3051
          ctx.cause = RemovalCause.EXPIRED;
1✔
3052
        }
3053
        if (ctx.cause != null) {
1✔
3054
          notifyEviction(ctx.nodeKey, ctx.oldValue, ctx.cause);
1✔
3055
          if (!computeIfAbsent) {
1✔
3056
            discardRefresh(kr);
1✔
3057
            ctx.removed = n;
1✔
3058
            n.retire();
1✔
3059
            return null;
1✔
3060
          }
3061
        }
3062

3063
        boolean wasEvicted = (ctx.cause != null);
1✔
3064
        try {
3065
          ctx.newValue = remappingFunction.apply(key,
1✔
3066
              (ctx.cause == null) ? ctx.oldValue : null);
1✔
3067

3068
          if (ctx.newValue == null) {
1✔
3069
            if (ctx.cause == null) {
1✔
3070
              ctx.cause = RemovalCause.EXPLICIT;
1✔
3071
            }
3072
            discardRefresh(kr);
1✔
3073
            ctx.removed = n;
1✔
3074
            n.retire();
1✔
3075
            return null;
1✔
3076
          }
3077

3078
          // If the caller flagged a same-instance return as a no-op (e.g., a refresh was rejected
3079
          // and should not touch the entry), skip the metadata updates below.
3080
          if ((ctx.hints != null) && ctx.hints.preserveTimestamps
1✔
3081
              && (ctx.newValue == ctx.oldValue) && (ctx.cause == null)) {
3082
            // Skip for query-style callers whose no-op path must leave any in-flight refresh intact
3083
            if (!ctx.hints.preserveRefresh) {
1✔
3084
              discardRefresh(kr);
1✔
3085
            }
3086
            return n;
1✔
3087
          }
3088

3089
          long varTime;
3090
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1✔
3091
          ctx.now = expirationTicker().read();
1✔
3092
          if (ctx.cause == null) {
1✔
3093
            if (ctx.newValue != ctx.oldValue) {
1✔
3094
              ctx.cause = RemovalCause.REPLACED;
1✔
3095
            }
3096
            varTime = expireAfterUpdate(n, key, ctx.newValue, expiry, ctx.now);
1✔
3097
          } else {
3098
            varTime = expireAfterCreate(key, ctx.newValue, expiry, ctx.now);
1✔
3099
          }
3100

3101
          if (ctx.newValue != ctx.oldValue) {
1✔
3102
            n.setValue(ctx.newValue, valueReferenceQueue());
1✔
3103
          }
3104
          n.setWeight(ctx.newWeight);
1✔
3105

3106
          long expirationTime = isComputingAsync(ctx.newValue)
1✔
3107
              ? ctx.now + ASYNC_EXPIRY
1✔
3108
              : ctx.now;
1✔
3109
          ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1✔
3110
          if (((ctx.cause != null) && ctx.cause.wasEvicted()) || ctx.exceedsTolerance) {
1✔
3111
            setWriteTime(n, expirationTime);
1✔
3112
          }
3113
          setAccessTime(n, expirationTime);
1✔
3114
          setVariableTime(n, varTime);
1✔
3115
          discardRefresh(kr);
1✔
3116
          return n;
1✔
3117
        } catch (Throwable e) {
1✔
3118
          discardRefresh(kr);
1✔
3119
          if (!wasEvicted) {
1✔
3120
            throw e;
1✔
3121
          }
3122
          ctx.newValue = null;
1✔
3123
          ctx.exception = e;
1✔
3124
          ctx.removed = n;
1✔
3125
          n.retire();
1✔
3126
          return null;
1✔
3127
        }
3128
      }
3129
    });
3130

3131
    if (ctx.cause != null) {
1✔
3132
      if (ctx.cause == RemovalCause.REPLACED) {
1✔
3133
        requireNonNull(ctx.newValue);
1✔
3134
        notifyOnReplace(key, ctx.oldValue, ctx.newValue);
1✔
3135
      } else {
3136
        if (ctx.cause.wasEvicted()) {
1✔
3137
          statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1✔
3138
        }
3139
        notifyRemoval(ctx.nodeKey, ctx.oldValue, ctx.cause);
1✔
3140
      }
3141
    }
3142

3143
    if (ctx.removed != null) {
1✔
3144
      afterWrite(new RemovalTask(ctx.removed));
1✔
3145
    } else if (node == null) {
1✔
3146
      // absent and not computable
3147
    } else if ((ctx.hints != null) && ctx.hints.preserveTimestamps) {
1✔
3148
      // The remapping was a signaled no-op; the node was not modified
3149
    } else if ((ctx.oldValue == null) && (ctx.cause == null)) {
1✔
3150
      afterWrite(new AddTask(node, ctx.newWeight));
1✔
3151
    } else {
3152
      int weightedDifference = ctx.newWeight - ctx.oldWeight;
1✔
3153
      if (ctx.exceedsTolerance || (weightedDifference != 0)) {
1✔
3154
        afterWrite(new UpdateTask(node, weightedDifference));
1✔
3155
      } else {
3156
        afterRead(node, ctx.now, /* recordHit= */ false);
1✔
3157
        if ((ctx.cause != null) && ctx.cause.wasEvicted()) {
1✔
3158
          scheduleDrainBuffers();
1✔
3159
        }
3160
      }
3161
    }
3162

3163
    if (ctx.exception != null) {
1✔
3164
      throw toUncheckedException(ctx.exception);
1✔
3165
    }
3166
    return ctx.newValue;
1✔
3167
  }
3168

3169
  @Override
3170
  public void forEach(BiConsumer<? super K, ? super V> action) {
3171
    requireNonNull(action);
1✔
3172

3173
    for (var iterator = new EntryIterator<>(this); iterator.hasNext();) {
1✔
3174
      action.accept(iterator.key, iterator.value);
1✔
3175
      iterator.advance();
1✔
3176
    }
3177
  }
1✔
3178

3179
  @Override
3180
  public Set<K> keySet() {
3181
    Set<K> ks = keySet;
1✔
3182
    return (ks == null) ? (keySet = new KeySetView<>(this)) : ks;
1✔
3183
  }
3184

3185
  @Override
3186
  public Collection<V> values() {
3187
    Collection<V> vs = values;
1✔
3188
    return (vs == null) ? (values = new ValuesView<>(this)) : vs;
1✔
3189
  }
3190

3191
  @Override
3192
  public Set<Entry<K, V>> entrySet() {
3193
    Set<Entry<K, V>> es = entrySet;
1✔
3194
    return (es == null) ? (entrySet = new EntrySetView<>(this)) : es;
1✔
3195
  }
3196

3197
  /**
3198
   * Object equality requires reflexive, symmetric, transitive, and consistency properties. Of
3199
   * these, symmetry and consistency require further clarification for how they are upheld.
3200
   * <p>
3201
   * The <i>consistency</i> property between invocations requires that the results are the same if
3202
   * there are no modifications to the information used. Therefore, usages should expect that this
3203
   * operation may return misleading results if either the maps or the data held by them is modified
3204
   * during the execution of this method. This characteristic allows for comparing the map sizes and
3205
   * assuming stable mappings, as done by {@link java.util.AbstractMap}-based maps.
3206
   * <p>
3207
   * The <i>symmetric</i> property requires that the result is the same for all implementations of
3208
   * {@link Map#equals(Object)}. That contract is defined in terms of the stable mappings provided
3209
   * by {@link #entrySet()}, meaning that the {@link #size()} optimization forces that the count is
3210
   * consistent with the mappings when used for an equality check.
3211
   * <p>
3212
   * The cache's {@link #size()} method may include entries that have expired or have been reference
3213
   * collected, but have not yet been removed from the backing map. An iteration over the map may
3214
   * trigger the removal of these dead entries when skipped over during traversal. To ensure
3215
   * consistency and symmetry, usages should call {@link #cleanUp()} before this method while no
3216
   * other concurrent operations are being performed on this cache. This is not done implicitly by
3217
   * {@link #size()} as many usages assume it to be instantaneous and lock-free. As a postcondition
3218
   * the iteration count is verified against the prescreened {@link #size()} so that a concurrent
3219
   * maintenance pass that drops dead entries during traversal is detected and reported as not
3220
   * equal, rather than silently returning {@code true} on the surviving subset.
3221
   */
3222
  @Override
3223
  public boolean equals(@Nullable Object o) {
3224
    if (o == this) {
1✔
3225
      return true;
1✔
3226
    } else if (!(o instanceof Map)) {
1✔
3227
      return false;
1✔
3228
    }
3229

3230
    var map = (Map<?, ?>) o;
1✔
3231
    int expectedSize = size();
1✔
3232
    if (map.size() != expectedSize) {
1✔
3233
      return false;
1✔
3234
    }
3235

3236
    long now = expirationTicker().read();
1✔
3237
    @Var int count = 0;
1✔
3238
    try {
3239
      for (var node : data.values()) {
1✔
3240
        K key = node.getKey();
1✔
3241
        V value = node.getValue();
1✔
3242
        if ((key == null) || (value == null)
1✔
3243
            || !node.isAlive() || hasExpired(node, now, value)) {
1✔
3244
          scheduleDrainBuffers();
1✔
3245
          return false;
1✔
3246
        } else {
3247
          var val = map.get(key);
1✔
3248
          if ((val == null) || ((val != value) && !val.equals(value))) {
1✔
3249
            return false;
1✔
3250
          }
3251
        }
3252
        count++;
1✔
3253
      }
1✔
3254
    } catch (ClassCastException | NullPointerException ignored) {
1✔
3255
      return false;
1✔
3256
    }
1✔
3257
    return (count == expectedSize);
1✔
3258
  }
3259

3260
  @Override
3261
  public int hashCode() {
3262
    @Var int hash = 0;
1✔
3263
    @Var boolean drain = false;
1✔
3264
    long now = expirationTicker().read();
1✔
3265
    for (var node : data.values()) {
1✔
3266
      K key = node.getKey();
1✔
3267
      V value = node.getValue();
1✔
3268
      if ((key == null) || (value == null)
1✔
3269
          || !node.isAlive() || hasExpired(node, now, value)) {
1✔
3270
        drain = true;
1✔
3271
      } else {
3272
        hash += key.hashCode() ^ value.hashCode();
1✔
3273
      }
3274
    }
1✔
3275
    if (drain) {
1✔
3276
      scheduleDrainBuffers();
1✔
3277
    }
3278
    return hash;
1✔
3279
  }
3280

3281
  @Override
3282
  public String toString() {
3283
    @Var boolean drain = false;
1✔
3284
    long now = expirationTicker().read();
1✔
3285
    var result = new StringBuilder().append('{');
1✔
3286
    for (var node : data.values()) {
1✔
3287
      K key = node.getKey();
1✔
3288
      V value = node.getValue();
1✔
3289
      if ((key == null) || (value == null)
1✔
3290
          || !node.isAlive() || hasExpired(node, now, value)) {
1✔
3291
        drain = true;
1✔
3292
      } else {
3293
        if (result.length() != 1) {
1✔
3294
          result.append(',').append(' ');
1✔
3295
        }
3296
        result.append((key == this) ? "(this Map)" : key);
1✔
3297
        result.append('=');
1✔
3298
        result.append((value == this) ? "(this Map)" : value);
1✔
3299
      }
3300
    }
1✔
3301
    if (drain) {
1✔
3302
      scheduleDrainBuffers();
1✔
3303
    }
3304
    return result.append('}').toString();
1✔
3305
  }
3306

3307
  /**
3308
   * Returns the computed result from the ordered traversal of the cache entries.
3309
   *
3310
   * @param hottest the coldest or hottest iteration order
3311
   * @param transformer a function that unwraps the value
3312
   * @param mappingFunction the mapping function to compute a value
3313
   * @return the computed value
3314
   */
3315
  @SuppressWarnings("GuardedByChecker")
3316
  <T> T evictionOrder(boolean hottest, Function<@Nullable V, @Nullable V> transformer,
3317
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3318
    Comparator<Node<K, V>> comparator = Comparator.comparingInt(node -> {
1✔
3319
      var keyRef = node.getKeyReferenceOrNull();
1✔
3320
      return ((keyRef == null) || !node.isAlive()) ? 0 : frequencySketch().frequency(keyRef);
1✔
3321
    });
3322
    Iterable<Node<K, V>> iterable;
3323
    if (hottest) {
1✔
3324
      iterable = () -> {
1✔
3325
        var secondary = PeekingIterator.comparing(
1✔
3326
            accessOrderProbationDeque().descendingIterator(),
1✔
3327
            accessOrderWindowDeque().descendingIterator(), comparator);
1✔
3328
        return PeekingIterator.concat(
1✔
3329
            accessOrderProtectedDeque().descendingIterator(), secondary);
1✔
3330
      };
3331
    } else {
3332
      iterable = () -> {
1✔
3333
        var primary = PeekingIterator.comparing(
1✔
3334
            accessOrderWindowDeque().iterator(), accessOrderProbationDeque().iterator(),
1✔
3335
            comparator.reversed());
1✔
3336
        return PeekingIterator.concat(primary, accessOrderProtectedDeque().iterator());
1✔
3337
      };
3338
    }
3339
    return snapshot(iterable, transformer, mappingFunction);
1✔
3340
  }
3341

3342
  /**
3343
   * Returns the computed result from the ordered traversal of the cache entries.
3344
   *
3345
   * @param oldest the youngest or oldest iteration order
3346
   * @param transformer a function that unwraps the value
3347
   * @param mappingFunction the mapping function to compute a value
3348
   * @return the computed value
3349
   */
3350
  @SuppressWarnings("GuardedByChecker")
3351
  <T> T expireAfterAccessOrder(boolean oldest, Function<@Nullable V, @Nullable V> transformer,
3352
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3353
    Iterable<Node<K, V>> iterable;
3354
    if (evicts()) {
1✔
3355
      iterable = () -> {
1✔
3356
        @Var Comparator<Node<K, V>> comparator = Comparator.comparingLong(Node::getAccessTime);
1✔
3357
        PeekingIterator<Node<K, V>> first;
3358
        PeekingIterator<Node<K, V>> second;
3359
        PeekingIterator<Node<K, V>> third;
3360
        if (oldest) {
1✔
3361
          comparator = comparator.reversed();
1✔
3362
          first = accessOrderWindowDeque().iterator();
1✔
3363
          second = accessOrderProbationDeque().iterator();
1✔
3364
          third = accessOrderProtectedDeque().iterator();
1✔
3365
        } else {
3366
          first = accessOrderWindowDeque().descendingIterator();
1✔
3367
          second = accessOrderProbationDeque().descendingIterator();
1✔
3368
          third = accessOrderProtectedDeque().descendingIterator();
1✔
3369
        }
3370
        return PeekingIterator.comparing(
1✔
3371
            PeekingIterator.comparing(first, second, comparator), third, comparator);
1✔
3372
      };
3373
    } else {
3374
      iterable = oldest
1✔
3375
          ? accessOrderWindowDeque()
1✔
3376
          : accessOrderWindowDeque()::descendingIterator;
1✔
3377
    }
3378
    return snapshot(iterable, transformer, mappingFunction);
1✔
3379
  }
3380

3381
  /**
3382
   * Returns the computed result from the ordered traversal of the cache entries.
3383
   *
3384
   * @param iterable the supplier of the entries in the cache
3385
   * @param transformer a function that unwraps the value
3386
   * @param mappingFunction the mapping function to compute a value
3387
   * @return the computed value
3388
   */
3389
  <T> T snapshot(Iterable<Node<K, V>> iterable, Function<@Nullable V, @Nullable V> transformer,
3390
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3391
    requireNonNull(mappingFunction);
1✔
3392
    requireNonNull(transformer);
1✔
3393
    requireNonNull(iterable);
1✔
3394

3395
    evictionLock.lock();
1✔
3396
    try {
3397
      maintenance(/* ignored */ null);
1✔
3398

3399
      // Obtain the iterator as late as possible for modification count checking
3400
      try (var stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(
1✔
3401
           iterable.iterator(), DISTINCT | ORDERED | NONNULL | IMMUTABLE), /* parallel= */ false)) {
1✔
3402
        return mappingFunction.apply(stream
1✔
3403
            .map(node -> nodeToCacheEntry(node, transformer, node.getPolicyWeight()))
1✔
3404
            .filter(Objects::nonNull));
1✔
3405
      }
3406
    } finally {
3407
      evictionLock.unlock();
1✔
3408
      rescheduleCleanUpIfIncomplete();
1✔
3409
    }
3410
  }
3411

3412
  /**
3413
   * Returns an entry for the given node if it can be used externally, else null. The weight is
3414
   * caller-supplied: snapshot callers hold evictionLock and read policyWeight (in sync with the
3415
   * drain thread); unlocked readers read weight, which may be stale for a concurrent in-place
3416
   * update (acceptable for a point-in-time CacheEntry).
3417
   */
3418
  @Nullable CacheEntry<K, V> nodeToCacheEntry(
3419
      Node<K, V> node, Function<@Nullable V, @Nullable V> transformer, int weight) {
3420
    V rawValue = node.getValue();
1✔
3421
    if (rawValue == null) {
1✔
3422
      return null;
1✔
3423
    }
3424
    V value = transformer.apply(rawValue);
1✔
3425
    K key = node.getKey();
1✔
3426
    long now;
3427
    if ((key == null) || (value == null) || !node.isAlive()
1✔
3428
        || hasExpired(node, (now = expirationTicker().read()), rawValue)) {
1✔
3429
      return null;
1✔
3430
    }
3431

3432
    @Var long expiresAfter = Long.MAX_VALUE;
1✔
3433
    if (expiresAfterAccess()) {
1✔
3434
      expiresAfter = Math.min(expiresAfter,
1✔
3435
          expiresAfterAccessNanos() - (now - node.getAccessTime()));
1✔
3436
    }
3437
    if (expiresAfterWrite()) {
1✔
3438
      expiresAfter = Math.min(expiresAfter,
1✔
3439
          expiresAfterWriteNanos() - ((now & ~1L) - (node.getWriteTime() & ~1L)));
1✔
3440
    }
3441
    if (expiresVariable()) {
1✔
3442
      expiresAfter = node.getVariableTime() - now;
1✔
3443
    }
3444

3445
    long refreshableAt = refreshAfterWrite()
1✔
3446
        ? (node.getWriteTime() & ~1L) + refreshAfterWriteNanos()
1✔
3447
        : now + Long.MAX_VALUE;
1✔
3448
    return SnapshotEntry.forEntry(key, value, now, weight, now + expiresAfter, refreshableAt);
1✔
3449
  }
3450

3451
  /** Mutable context for passing state between a lambda and the caller. */
3452
  static final class EvictContext<V> {
1✔
3453
    @Nullable RemovalCause cause;
3454
    @Nullable V value;
3455
    boolean resurrect;
3456
    boolean removed;
3457
    int oldWeight;
3458
  }
3459

3460
  /** Mutable context for passing state between a lambda and the caller. */
3461
  static final class RemoveContext<K, V> {
1✔
3462
    @Nullable K oldKey;
3463
    @Nullable V oldValue;
3464
    @Nullable Node<K, V> node;
3465
    @Nullable RemovalCause cause;
3466
    int oldWeight;
3467
  }
3468

3469
  /** Mutable context for passing state between a lambda and the caller. */
3470
  static final class ReplaceContext<K, V> {
1✔
3471
    @Nullable K nodeKey;
3472
    @Nullable V oldValue;
3473

3474
    long now;
3475
    int oldWeight;
3476
    boolean exceedsTolerance;
3477
  }
3478

3479
  /** Mutable context for passing state between a lambda and the caller. */
3480
  static final class ComputeContext<K, V> {
3481
    @Nullable K nodeKey;
3482
    @Nullable V oldValue;
3483
    @Nullable V newValue;
3484
    @Nullable Node<K, V> removed;
3485
    @Nullable RemovalCause cause;
3486
    @Nullable Throwable exception;
3487
    @Nullable RemapHints hints;
3488

3489
    long now;
3490
    int oldWeight;
3491
    int newWeight;
3492
    boolean exceedsTolerance;
3493

3494
    ComputeContext(long now) {
1✔
3495
      this.now = now;
1✔
3496
    }
1✔
3497
  }
3498

3499
  /** A function that produces an unmodifiable map up to the limit in stream order. */
3500
  static final class SizeLimiter<K, V> implements Function<Stream<CacheEntry<K, V>>, Map<K, V>> {
3501
    private final int expectedSize;
3502
    private final long limit;
3503

3504
    SizeLimiter(int expectedSize, long limit) {
1✔
3505
      requireArgument(limit >= 0);
1✔
3506
      this.expectedSize = expectedSize;
1✔
3507
      this.limit = limit;
1✔
3508
    }
1✔
3509

3510
    @Override
3511
    public Map<K, V> apply(Stream<CacheEntry<K, V>> stream) {
3512
      var map = new LinkedHashMap<K, V>(calculateHashMapCapacity(expectedSize));
1✔
3513
      stream.limit(limit).forEach(entry -> map.put(entry.getKey(), entry.getValue()));
1✔
3514
      return Collections.unmodifiableMap(map);
1✔
3515
    }
3516
  }
3517

3518
  /** A function that produces an unmodifiable map up to the weighted limit in stream order. */
3519
  static final class WeightLimiter<K, V> implements Function<Stream<CacheEntry<K, V>>, Map<K, V>> {
3520
    private final long weightLimit;
3521

3522
    private long weightedSize;
3523

3524
    WeightLimiter(long weightLimit) {
1✔
3525
      requireArgument(weightLimit >= 0);
1✔
3526
      this.weightLimit = weightLimit;
1✔
3527
    }
1✔
3528

3529
    @Override
3530
    public Map<K, V> apply(Stream<CacheEntry<K, V>> stream) {
3531
      var map = new LinkedHashMap<K, V>();
1✔
3532
      stream.takeWhile(entry -> {
1✔
3533
        weightedSize = Math.addExact(weightedSize, entry.weight());
1✔
3534
        return (weightedSize <= weightLimit);
1✔
3535
      }).forEach(entry -> map.put(entry.getKey(), entry.getValue()));
1✔
3536
      return Collections.unmodifiableMap(map);
1✔
3537
    }
3538
  }
3539

3540
  /** An adapter to safely externalize the keys. */
3541
  static final class KeySetView<K, V> extends AbstractSet<K> {
3542
    final BoundedLocalCache<K, V> cache;
3543

3544
    KeySetView(BoundedLocalCache<K, V> cache) {
1✔
3545
      this.cache = requireNonNull(cache);
1✔
3546
    }
1✔
3547

3548
    @Override
3549
    public int size() {
3550
      return cache.size();
1✔
3551
    }
3552

3553
    @Override
3554
    public void clear() {
3555
      cache.clear();
1✔
3556
    }
1✔
3557

3558
    @Override
3559
    @SuppressWarnings("SuspiciousMethodCalls")
3560
    public boolean contains(Object o) {
3561
      return cache.containsKey(o);
1✔
3562
    }
3563

3564
    @Override
3565
    public boolean removeAll(Collection<?> collection) {
3566
      requireNonNull(collection);
1✔
3567
      @Var boolean modified = false;
1✔
3568
      if (cache.collectKeys() || ((collection instanceof Set<?>) && (collection.size() > size()))) {
1✔
3569
        for (K key : this) {
1✔
3570
          if (collection.contains(key)) {
1✔
3571
            modified |= remove(key);
1✔
3572
          }
3573
        }
1✔
3574
      } else {
3575
        for (var item : collection) {
1✔
3576
          modified |= (item != null) && remove(item);
1✔
3577
        }
1✔
3578
      }
3579
      return modified;
1✔
3580
    }
3581

3582
    @Override
3583
    public boolean remove(Object o) {
3584
      return (cache.remove(o) != null);
1✔
3585
    }
3586

3587
    @Override
3588
    public boolean removeIf(Predicate<? super K> filter) {
3589
      requireNonNull(filter);
1✔
3590
      @Var boolean modified = false;
1✔
3591
      for (K key : this) {
1✔
3592
        if (filter.test(key) && remove(key)) {
1✔
3593
          modified = true;
1✔
3594
        }
3595
      }
1✔
3596
      return modified;
1✔
3597
    }
3598

3599
    @Override
3600
    public boolean retainAll(Collection<?> collection) {
3601
      requireNonNull(collection);
1✔
3602
      @Var boolean modified = false;
1✔
3603
      for (K key : this) {
1✔
3604
        if (!collection.contains(key) && remove(key)) {
1✔
3605
          modified = true;
1✔
3606
        }
3607
      }
1✔
3608
      return modified;
1✔
3609
    }
3610

3611
    @Override
3612
    public Iterator<K> iterator() {
3613
      return new KeyIterator<>(cache);
1✔
3614
    }
3615

3616
    @Override
3617
    public Spliterator<K> spliterator() {
3618
      return new KeySpliterator<>(cache);
1✔
3619
    }
3620
  }
3621

3622
  /** An adapter to safely externalize the key iterator. */
3623
  static final class KeyIterator<K, V> implements Iterator<K> {
3624
    final EntryIterator<K, V> iterator;
3625

3626
    KeyIterator(BoundedLocalCache<K, V> cache) {
1✔
3627
      this.iterator = new EntryIterator<>(cache);
1✔
3628
    }
1✔
3629

3630
    @Override
3631
    public boolean hasNext() {
3632
      return iterator.hasNext();
1✔
3633
    }
3634

3635
    @Override
3636
    public K next() {
3637
      return iterator.nextKey();
1✔
3638
    }
3639

3640
    @Override
3641
    public void remove() {
3642
      iterator.remove();
1✔
3643
    }
1✔
3644
  }
3645

3646
  /** An adapter to safely externalize the key spliterator. */
3647
  static final class KeySpliterator<K, V> implements Spliterator<K> {
3648
    final Spliterator<Node<K, V>> spliterator;
3649
    final BoundedLocalCache<K, V> cache;
3650

3651
    KeySpliterator(BoundedLocalCache<K, V> cache) {
3652
      this(cache, cache.data.values().spliterator());
1✔
3653
    }
1✔
3654

3655
    KeySpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1✔
3656
      this.spliterator = requireNonNull(spliterator);
1✔
3657
      this.cache = requireNonNull(cache);
1✔
3658
    }
1✔
3659

3660
    @Override
3661
    public void forEachRemaining(Consumer<? super K> action) {
3662
      requireNonNull(action);
1✔
3663
      Consumer<Node<K, V>> consumer = node -> {
1✔
3664
        K key = node.getKey();
1✔
3665
        V value = node.getValue();
1✔
3666
        long now = cache.expirationTicker().read();
1✔
3667
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
3668
          cache.scheduleDrainBuffers();
1✔
3669
        } else if (node.isAlive()) {
1✔
3670
          action.accept(key);
1✔
3671
        }
3672
      };
1✔
3673
      spliterator.forEachRemaining(consumer);
1✔
3674
    }
1✔
3675

3676
    @Override
3677
    public boolean tryAdvance(Consumer<? super K> action) {
3678
      requireNonNull(action);
1✔
3679
      boolean[] advanced = { false };
1✔
3680
      Consumer<Node<K, V>> consumer = node -> {
1✔
3681
        K key = node.getKey();
1✔
3682
        V value = node.getValue();
1✔
3683
        long now = cache.expirationTicker().read();
1✔
3684
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
3685
          cache.scheduleDrainBuffers();
1✔
3686
        } else if (node.isAlive()) {
1✔
3687
          action.accept(key);
1✔
3688
          advanced[0] = true;
1✔
3689
        }
3690
      };
1✔
3691
      while (spliterator.tryAdvance(consumer)) {
1✔
3692
        if (advanced[0]) {
1✔
3693
          return true;
1✔
3694
        }
3695
      }
3696
      return false;
1✔
3697
    }
3698

3699
    @Override
3700
    public @Nullable Spliterator<K> trySplit() {
3701
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1✔
3702
      return (split == null) ? null : new KeySpliterator<>(cache, split);
1✔
3703
    }
3704

3705
    @Override
3706
    public long estimateSize() {
3707
      return spliterator.estimateSize();
1✔
3708
    }
3709

3710
    @Override
3711
    public int characteristics() {
3712
      return DISTINCT | CONCURRENT | NONNULL;
1✔
3713
    }
3714
  }
3715

3716
  /** An adapter to safely externalize the values. */
3717
  static final class ValuesView<K, V> extends AbstractCollection<V> {
3718
    final BoundedLocalCache<K, V> cache;
3719

3720
    ValuesView(BoundedLocalCache<K, V> cache) {
1✔
3721
      this.cache = requireNonNull(cache);
1✔
3722
    }
1✔
3723

3724
    @Override
3725
    public int size() {
3726
      return cache.size();
1✔
3727
    }
3728

3729
    @Override
3730
    public void clear() {
3731
      cache.clear();
1✔
3732
    }
1✔
3733

3734
    @Override
3735
    @SuppressWarnings("SuspiciousMethodCalls")
3736
    public boolean contains(Object o) {
3737
      return cache.containsValue(o);
1✔
3738
    }
3739

3740
    @Override
3741
    public boolean removeAll(Collection<?> collection) {
3742
      requireNonNull(collection);
1✔
3743
      @Var boolean modified = false;
1✔
3744
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1✔
3745
        var key = requireNonNull(iterator.key);
1✔
3746
        var value = requireNonNull(iterator.value);
1✔
3747
        if (collection.contains(value) && cache.remove(key, value)) {
1✔
3748
          modified = true;
1✔
3749
        }
3750
        iterator.advance();
1✔
3751
      }
1✔
3752
      return modified;
1✔
3753
    }
3754

3755
    @Override
3756
    public boolean remove(@Nullable Object o) {
3757
      if (o == null) {
1✔
3758
        return false;
1✔
3759
      }
3760
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1✔
3761
        var key = requireNonNull(iterator.key);
1✔
3762
        var node = requireNonNull(iterator.next);
1✔
3763
        var value = requireNonNull(iterator.value);
1✔
3764
        if (node.containsValue(o) && cache.remove(key, value)) {
1✔
3765
          return true;
1✔
3766
        }
3767
        iterator.advance();
1✔
3768
      }
1✔
3769
      return false;
1✔
3770
    }
3771

3772
    @Override
3773
    public boolean removeIf(Predicate<? super V> filter) {
3774
      requireNonNull(filter);
1✔
3775
      @Var boolean modified = false;
1✔
3776
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1✔
3777
        var value = requireNonNull(iterator.value);
1✔
3778
        if (filter.test(value)) {
1✔
3779
          var key = requireNonNull(iterator.key);
1✔
3780
          modified |= cache.remove(key, value);
1✔
3781
        }
3782
        iterator.advance();
1✔
3783
      }
1✔
3784
      return modified;
1✔
3785
    }
3786

3787
    @Override
3788
    public boolean retainAll(Collection<?> collection) {
3789
      requireNonNull(collection);
1✔
3790
      @Var boolean modified = false;
1✔
3791
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1✔
3792
        var key = requireNonNull(iterator.key);
1✔
3793
        var value = requireNonNull(iterator.value);
1✔
3794
        if (!collection.contains(value) && cache.remove(key, value)) {
1✔
3795
          modified = true;
1✔
3796
        }
3797
        iterator.advance();
1✔
3798
      }
1✔
3799
      return modified;
1✔
3800
    }
3801

3802
    @Override
3803
    public Iterator<V> iterator() {
3804
      return new ValueIterator<>(cache);
1✔
3805
    }
3806

3807
    @Override
3808
    public Spliterator<V> spliterator() {
3809
      return new ValueSpliterator<>(cache);
1✔
3810
    }
3811
  }
3812

3813
  /** An adapter to safely externalize the value iterator. */
3814
  static final class ValueIterator<K, V> implements Iterator<V> {
3815
    final EntryIterator<K, V> iterator;
3816

3817
    ValueIterator(BoundedLocalCache<K, V> cache) {
1✔
3818
      this.iterator = new EntryIterator<>(cache);
1✔
3819
    }
1✔
3820

3821
    @Override
3822
    public boolean hasNext() {
3823
      return iterator.hasNext();
1✔
3824
    }
3825

3826
    @Override
3827
    public V next() {
3828
      return iterator.nextValue();
1✔
3829
    }
3830

3831
    @Override
3832
    public void remove() {
3833
      iterator.remove();
1✔
3834
    }
1✔
3835
  }
3836

3837
  /** An adapter to safely externalize the value spliterator. */
3838
  static final class ValueSpliterator<K, V> implements Spliterator<V> {
3839
    final Spliterator<Node<K, V>> spliterator;
3840
    final BoundedLocalCache<K, V> cache;
3841

3842
    ValueSpliterator(BoundedLocalCache<K, V> cache) {
3843
      this(cache, cache.data.values().spliterator());
1✔
3844
    }
1✔
3845

3846
    ValueSpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1✔
3847
      this.spliterator = requireNonNull(spliterator);
1✔
3848
      this.cache = requireNonNull(cache);
1✔
3849
    }
1✔
3850

3851
    @Override
3852
    public void forEachRemaining(Consumer<? super V> action) {
3853
      requireNonNull(action);
1✔
3854
      Consumer<Node<K, V>> consumer = node -> {
1✔
3855
        K key = node.getKey();
1✔
3856
        V value = node.getValue();
1✔
3857
        long now = cache.expirationTicker().read();
1✔
3858
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
3859
          cache.scheduleDrainBuffers();
1✔
3860
        } else if (node.isAlive()) {
1✔
3861
          action.accept(value);
1✔
3862
        }
3863
      };
1✔
3864
      spliterator.forEachRemaining(consumer);
1✔
3865
    }
1✔
3866

3867
    @Override
3868
    public boolean tryAdvance(Consumer<? super V> action) {
3869
      requireNonNull(action);
1✔
3870
      boolean[] advanced = { false };
1✔
3871
      Consumer<Node<K, V>> consumer = node -> {
1✔
3872
        K key = node.getKey();
1✔
3873
        V value = node.getValue();
1✔
3874
        long now = cache.expirationTicker().read();
1✔
3875
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
3876
          cache.scheduleDrainBuffers();
1✔
3877
        } else if (node.isAlive()) {
1✔
3878
          action.accept(value);
1✔
3879
          advanced[0] = true;
1✔
3880
        }
3881
      };
1✔
3882
      while (spliterator.tryAdvance(consumer)) {
1✔
3883
        if (advanced[0]) {
1✔
3884
          return true;
1✔
3885
        }
3886
      }
3887
      return false;
1✔
3888
    }
3889

3890
    @Override
3891
    public @Nullable Spliterator<V> trySplit() {
3892
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1✔
3893
      return (split == null) ? null : new ValueSpliterator<>(cache, split);
1✔
3894
    }
3895

3896
    @Override
3897
    public long estimateSize() {
3898
      return spliterator.estimateSize();
1✔
3899
    }
3900

3901
    @Override
3902
    public int characteristics() {
3903
      return CONCURRENT | NONNULL;
1✔
3904
    }
3905
  }
3906

3907
  /** An adapter to safely externalize the entries. */
3908
  static final class EntrySetView<K, V> extends AbstractSet<Entry<K, V>> {
3909
    final BoundedLocalCache<K, V> cache;
3910

3911
    EntrySetView(BoundedLocalCache<K, V> cache) {
1✔
3912
      this.cache = requireNonNull(cache);
1✔
3913
    }
1✔
3914

3915
    @Override
3916
    public int size() {
3917
      return cache.size();
1✔
3918
    }
3919

3920
    @Override
3921
    public void clear() {
3922
      cache.clear();
1✔
3923
    }
1✔
3924

3925
    @Override
3926
    public boolean contains(Object o) {
3927
      if (!(o instanceof Entry<?, ?>)) {
1✔
3928
        return false;
1✔
3929
      }
3930
      var entry = (Entry<?, ?>) o;
1✔
3931
      var key = entry.getKey();
1✔
3932
      var value = entry.getValue();
1✔
3933
      if ((key == null) || (value == null)) {
1✔
3934
        return false;
1✔
3935
      }
3936
      Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1✔
3937
      if (node == null) {
1✔
3938
        return false;
1✔
3939
      }
3940
      V nodeValue = node.getValue();
1✔
3941
      return (nodeValue != null) && node.containsValue(value)
1✔
3942
          && !cache.hasExpired(node, cache.expirationTicker().read(), nodeValue);
1✔
3943
    }
3944

3945
    @Override
3946
    public boolean removeAll(Collection<?> collection) {
3947
      requireNonNull(collection);
1✔
3948
      @Var boolean modified = false;
1✔
3949
      if (cache.collectKeys() || ((collection instanceof Set<?>) && (collection.size() > size()))) {
1✔
3950
        for (var entry : this) {
1✔
3951
          if (collection.contains(entry)) {
1✔
3952
            modified |= remove(entry);
1✔
3953
          }
3954
        }
1✔
3955
      } else {
3956
        for (var item : collection) {
1✔
3957
          modified |= (item != null) && remove(item);
1✔
3958
        }
1✔
3959
      }
3960
      return modified;
1✔
3961
    }
3962

3963
    @Override
3964
    @SuppressWarnings("SuspiciousMethodCalls")
3965
    public boolean remove(Object o) {
3966
      if (!(o instanceof Entry<?, ?>)) {
1✔
3967
        return false;
1✔
3968
      }
3969
      var entry = (Entry<?, ?>) o;
1✔
3970
      var key = entry.getKey();
1✔
3971
      return (key != null) && cache.remove(key, entry.getValue());
1✔
3972
    }
3973

3974
    @Override
3975
    public boolean removeIf(Predicate<? super Entry<K, V>> filter) {
3976
      requireNonNull(filter);
1✔
3977
      @Var boolean modified = false;
1✔
3978
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1✔
3979
        var key = requireNonNull(iterator.key);
1✔
3980
        var value = requireNonNull(iterator.value);
1✔
3981
        if (filter.test(Map.entry(key, value))) {
1✔
3982
          modified |= cache.remove(key, value);
1✔
3983
        }
3984
        iterator.advance();
1✔
3985
      }
1✔
3986
      return modified;
1✔
3987
    }
3988

3989
    @Override
3990
    public boolean retainAll(Collection<?> collection) {
3991
      requireNonNull(collection);
1✔
3992
      @Var boolean modified = false;
1✔
3993
      for (var entry : this) {
1✔
3994
        if (!collection.contains(entry) && remove(entry)) {
1✔
3995
          modified = true;
1✔
3996
        }
3997
      }
1✔
3998
      return modified;
1✔
3999
    }
4000

4001
    @Override
4002
    public Iterator<Entry<K, V>> iterator() {
4003
      return new EntryIterator<>(cache);
1✔
4004
    }
4005

4006
    @Override
4007
    public Spliterator<Entry<K, V>> spliterator() {
4008
      return new EntrySpliterator<>(cache);
1✔
4009
    }
4010
  }
4011

4012
  /** An adapter to safely externalize the entry iterator. */
4013
  static final class EntryIterator<K, V> implements Iterator<Entry<K, V>> {
4014
    final BoundedLocalCache<K, V> cache;
4015
    final Iterator<Node<K, V>> iterator;
4016

4017
    @Nullable K key;
4018
    @Nullable V value;
4019
    @Nullable K removalKey;
4020
    @Nullable Node<K, V> next;
4021

4022
    EntryIterator(BoundedLocalCache<K, V> cache) {
1✔
4023
      this.iterator = cache.data.values().iterator();
1✔
4024
      this.cache = cache;
1✔
4025
    }
1✔
4026

4027
    @Override
4028
    public boolean hasNext() {
4029
      if (next != null) {
1✔
4030
        return true;
1✔
4031
      }
4032

4033
      long now = cache.expirationTicker().read();
1✔
4034
      while (iterator.hasNext()) {
1✔
4035
        next = iterator.next();
1✔
4036
        value = next.getValue();
1✔
4037
        key = next.getKey();
1✔
4038

4039
        boolean evictable = (key == null) || (value == null) || cache.hasExpired(next, now, value);
1✔
4040
        if (evictable || !next.isAlive()) {
1✔
4041
          if (evictable) {
1✔
4042
            cache.scheduleDrainBuffers();
1✔
4043
          }
4044
          advance();
1✔
4045
          continue;
1✔
4046
        }
4047
        return true;
1✔
4048
      }
4049
      return false;
1✔
4050
    }
4051

4052
    /** Invalidates the current position so that the iterator may compute the next position. */
4053
    void advance() {
4054
      value = null;
1✔
4055
      next = null;
1✔
4056
      key = null;
1✔
4057
    }
1✔
4058

4059
    K nextKey() {
4060
      if (!hasNext()) {
1✔
4061
        throw new NoSuchElementException();
1✔
4062
      }
4063
      removalKey = key;
1✔
4064
      advance();
1✔
4065
      return requireNonNull(removalKey);
1✔
4066
    }
4067

4068
    V nextValue() {
4069
      if (!hasNext()) {
1✔
4070
        throw new NoSuchElementException();
1✔
4071
      }
4072
      removalKey = key;
1✔
4073
      V val = value;
1✔
4074
      advance();
1✔
4075
      return requireNonNull(val);
1✔
4076
    }
4077

4078
    @Override
4079
    public Entry<K, V> next() {
4080
      if (!hasNext()) {
1✔
4081
        throw new NoSuchElementException();
1✔
4082
      }
4083
      var entry = new WriteThroughEntry<K, @NonNull V>(
1✔
4084
          cache, requireNonNull(key), requireNonNull(value));
1✔
4085
      removalKey = key;
1✔
4086
      advance();
1✔
4087
      return entry;
1✔
4088
    }
4089

4090
    @Override
4091
    public void remove() {
4092
      if (removalKey == null) {
1✔
4093
        throw new IllegalStateException();
1✔
4094
      }
4095
      cache.remove(removalKey);
1✔
4096
      removalKey = null;
1✔
4097
    }
1✔
4098
  }
4099

4100
  /** An adapter to safely externalize the entry spliterator. */
4101
  static final class EntrySpliterator<K, V> implements Spliterator<Entry<K, V>> {
4102
    final Spliterator<Node<K, V>> spliterator;
4103
    final BoundedLocalCache<K, V> cache;
4104

4105
    EntrySpliterator(BoundedLocalCache<K, V> cache) {
4106
      this(cache, cache.data.values().spliterator());
1✔
4107
    }
1✔
4108

4109
    EntrySpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1✔
4110
      this.spliterator = requireNonNull(spliterator);
1✔
4111
      this.cache = requireNonNull(cache);
1✔
4112
    }
1✔
4113

4114
    @Override
4115
    public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
4116
      requireNonNull(action);
1✔
4117
      Consumer<Node<K, V>> consumer = node -> {
1✔
4118
        K key = node.getKey();
1✔
4119
        V value = node.getValue();
1✔
4120
        long now = cache.expirationTicker().read();
1✔
4121
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
4122
          cache.scheduleDrainBuffers();
1✔
4123
        } else if (node.isAlive()) {
1✔
4124
          action.accept(new WriteThroughEntry<>(cache, key, value));
1✔
4125
        }
4126
      };
1✔
4127
      spliterator.forEachRemaining(consumer);
1✔
4128
    }
1✔
4129

4130
    @Override
4131
    public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
4132
      requireNonNull(action);
1✔
4133
      boolean[] advanced = { false };
1✔
4134
      Consumer<Node<K, V>> consumer = node -> {
1✔
4135
        K key = node.getKey();
1✔
4136
        V value = node.getValue();
1✔
4137
        long now = cache.expirationTicker().read();
1✔
4138
        if ((key == null) || (value == null) || cache.hasExpired(node, now, value)) {
1✔
4139
          cache.scheduleDrainBuffers();
1✔
4140
        } else if (node.isAlive()) {
1✔
4141
          action.accept(new WriteThroughEntry<>(cache, key, value));
1✔
4142
          advanced[0] = true;
1✔
4143
        }
4144
      };
1✔
4145
      while (spliterator.tryAdvance(consumer)) {
1✔
4146
        if (advanced[0]) {
1✔
4147
          return true;
1✔
4148
        }
4149
      }
4150
      return false;
1✔
4151
    }
4152

4153
    @Override
4154
    public @Nullable Spliterator<Entry<K, V>> trySplit() {
4155
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1✔
4156
      return (split == null) ? null : new EntrySpliterator<>(cache, split);
1✔
4157
    }
4158

4159
    @Override
4160
    public long estimateSize() {
4161
      return spliterator.estimateSize();
1✔
4162
    }
4163

4164
    @Override
4165
    public int characteristics() {
4166
      return DISTINCT | CONCURRENT | NONNULL;
1✔
4167
    }
4168
  }
4169

4170
  /** A reusable task that performs the maintenance work; used to avoid wrapping by ForkJoinPool. */
4171
  static final class PerformCleanupTask extends ForkJoinTask<@Nullable Void> implements Runnable {
4172
    private static final long serialVersionUID = 1L;
4173

4174
    final WeakReference<BoundedLocalCache<?, ?>> reference;
4175

4176
    PerformCleanupTask(BoundedLocalCache<?, ?> cache) {
1✔
4177
      reference = new WeakReference<>(cache);
1✔
4178
    }
1✔
4179

4180
    @Override
4181
    protected boolean exec() {
4182
      try {
4183
        run();
1✔
4184
      } catch (Throwable t) {
1✔
4185
        logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", t);
1✔
4186
      }
1✔
4187

4188
      // Indicates that the task has not completed to allow subsequent submissions to execute
4189
      return false;
1✔
4190
    }
4191

4192
    @Override
4193
    public void run() {
4194
      BoundedLocalCache<?, ?> cache = reference.get();
1✔
4195
      if (cache != null) {
1✔
4196
        cache.performCleanUp(/* ignored */ null);
1✔
4197
      }
4198
    }
1✔
4199

4200
    /**
4201
     * This method cannot be ignored due to being final, so a hostile user supplied Executor could
4202
     * forcibly complete the task and halt future executions. There are easier ways to intentionally
4203
     * harm a system, so this is assumed to not happen in practice.
4204
     */
4205
    // public final void quietlyComplete() {}
4206

UNCOV
4207
    @Override public void complete(@Nullable Void value) {}
×
UNCOV
4208
    @Override public void setRawResult(@Nullable Void value) {}
×
UNCOV
4209
    @Override public @Nullable Void getRawResult() { return null; }
×
UNCOV
4210
    @Override public void completeExceptionally(@Nullable Throwable t) {}
×
UNCOV
4211
    @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; }
×
4212
  }
4213

4214
  /** Creates a serialization proxy based on the common configuration shared by all cache types. */
4215
  static <K, V> SerializationProxy<K, V> makeSerializationProxy(BoundedLocalCache<?, ?> cache) {
4216
    var proxy = new SerializationProxy<K, V>();
1✔
4217
    proxy.weakKeys = cache.collectKeys();
1✔
4218
    proxy.weakValues = cache.nodeFactory.weakValues();
1✔
4219
    proxy.softValues = cache.nodeFactory.softValues();
1✔
4220
    proxy.isRecordingStats = cache.isRecordingStats();
1✔
4221
    proxy.evictionListener = cache.evictionListener;
1✔
4222
    proxy.removalListener = cache.removalListener();
1✔
4223
    proxy.ticker = cache.expirationTicker();
1✔
4224
    if (cache.expiresAfterAccess()) {
1✔
4225
      proxy.expiresAfterAccessNanos = cache.expiresAfterAccessNanos();
1✔
4226
    }
4227
    if (cache.expiresAfterWrite()) {
1✔
4228
      proxy.expiresAfterWriteNanos = cache.expiresAfterWriteNanos();
1✔
4229
    }
4230
    if (cache.expiresVariable()) {
1✔
4231
      proxy.expiry = cache.expiry();
1✔
4232
    }
4233
    if (cache.refreshAfterWrite()) {
1✔
4234
      proxy.refreshAfterWriteNanos = cache.refreshAfterWriteNanos();
1✔
4235
    }
4236
    if (cache.evicts()) {
1✔
4237
      if (cache.isWeighted) {
1✔
4238
        proxy.weigher = cache.weigher;
1✔
4239
        proxy.maximumWeight = cache.maximum();
1✔
4240
      } else {
4241
        proxy.maximumSize = cache.maximum();
1✔
4242
      }
4243
    }
4244
    proxy.cacheLoader = cache.cacheLoader;
1✔
4245
    proxy.async = cache.isAsync;
1✔
4246
    return proxy;
1✔
4247
  }
4248

4249
  /* --------------- Manual Cache --------------- */
4250

4251
  static class BoundedLocalManualCache<K, V> implements LocalManualCache<K, V>, Serializable {
4252
    private static final long serialVersionUID = 1;
4253

4254
    final BoundedLocalCache<K, V> cache;
4255

4256
    @Nullable Policy<K, V> policy;
4257

4258
    BoundedLocalManualCache(Caffeine<K, V> builder) {
4259
      this(builder, null);
1✔
4260
    }
1✔
4261

4262
    BoundedLocalManualCache(Caffeine<K, V> builder, @Nullable CacheLoader<? super K, V> loader) {
1✔
4263
      cache = LocalCacheFactory.newBoundedLocalCache(builder, loader, /* isAsync= */ false);
1✔
4264
    }
1✔
4265

4266
    @Override
4267
    public final BoundedLocalCache<K, V> cache() {
4268
      return cache;
1✔
4269
    }
4270

4271
    @Override
4272
    public final Policy<K, V> policy() {
4273
      if (policy == null) {
1✔
4274
        Function<@Nullable V, @Nullable V> identity = v -> v;
1✔
4275
        policy = new BoundedPolicy<>(cache, identity, cache.isWeighted);
1✔
4276
      }
4277
      return policy;
1✔
4278
    }
4279

4280
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4281
      throw new InvalidObjectException("Proxy required");
1✔
4282
    }
4283

4284
    private Object writeReplace() {
4285
      return makeSerializationProxy(cache);
1✔
4286
    }
4287
  }
4288

4289
  @SuppressWarnings({"NullableOptional",
4290
    "OptionalAssignedToNull", "OptionalUsedAsFieldOrParameterType"})
4291
  static final class BoundedPolicy<K, V> implements Policy<K, V> {
4292
    final Function<@Nullable V, @Nullable V> transformer;
4293
    final BoundedLocalCache<K, V> cache;
4294
    final boolean isWeighted;
4295

4296
    @Nullable Optional<Eviction<K, V>> eviction;
4297
    @Nullable Optional<FixedRefresh<K, V>> refreshes;
4298
    @Nullable Optional<FixedExpiration<K, V>> afterWrite;
4299
    @Nullable Optional<FixedExpiration<K, V>> afterAccess;
4300
    @Nullable Optional<VarExpiration<K, V>> variable;
4301

4302
    BoundedPolicy(BoundedLocalCache<K, V> cache,
4303
        Function<@Nullable V, @Nullable V> transformer, boolean isWeighted) {
1✔
4304
      this.transformer = transformer;
1✔
4305
      this.isWeighted = isWeighted;
1✔
4306
      this.cache = cache;
1✔
4307
    }
1✔
4308

4309
    @Override public boolean isRecordingStats() {
4310
      return cache.isRecordingStats();
1✔
4311
    }
4312
    @Override public @Nullable V getIfPresentQuietly(K key) {
4313
      return transformer.apply(cache.getIfPresentQuietly(key));
1✔
4314
    }
4315
    @SuppressWarnings("GuardedByChecker")
4316
    @Override public @Nullable CacheEntry<K, V> getEntryIfPresentQuietly(K key) {
4317
      Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1✔
4318
      return (node == null) ? null : cache.nodeToCacheEntry(node, transformer, node.getWeight());
1✔
4319
    }
4320
    @SuppressWarnings("Java9CollectionFactory")
4321
    @Override public Map<K, CompletableFuture<V>> refreshes() {
4322
      var refreshes = cache.refreshes;
1✔
4323
      if ((refreshes == null) || refreshes.isEmpty()) {
1✔
4324
        @SuppressWarnings({"ImmutableMapOf", "RedundantUnmodifiable"})
4325
        Map<K, CompletableFuture<V>> emptyMap = Collections.unmodifiableMap(Collections.emptyMap());
1✔
4326
        return emptyMap;
1✔
4327
      } else if (cache.collectKeys()) {
1✔
4328
        var inFlight = new IdentityHashMap<K, CompletableFuture<V>>(refreshes.size());
1✔
4329
        for (var entry : refreshes.entrySet()) {
1✔
4330
          @SuppressWarnings("unchecked")
4331
          @Nullable K key = ((InternalReference<K>) entry.getKey()).get();
1✔
4332
          @SuppressWarnings("unchecked")
4333
          var future = (CompletableFuture<V>) entry.getValue();
1✔
4334
          if (key != null) {
1✔
4335
            inFlight.put(key, future);
1✔
4336
          }
4337
        }
1✔
4338
        return Collections.unmodifiableMap(inFlight);
1✔
4339
      }
4340
      @SuppressWarnings("unchecked")
4341
      var castedRefreshes = (Map<K, CompletableFuture<V>>) (Object) refreshes;
1✔
4342
      return Collections.unmodifiableMap(new HashMap<>(castedRefreshes));
1✔
4343
    }
4344
    @Override public Optional<Eviction<K, V>> eviction() {
4345
      return cache.evicts()
1✔
4346
          ? (eviction == null) ? (eviction = Optional.of(new BoundedEviction())) : eviction
1✔
4347
          : Optional.empty();
1✔
4348
    }
4349
    @Override public Optional<FixedExpiration<K, V>> expireAfterAccess() {
4350
      if (!cache.expiresAfterAccess()) {
1✔
4351
        return Optional.empty();
1✔
4352
      }
4353
      return (afterAccess == null)
1✔
4354
          ? (afterAccess = Optional.of(new BoundedExpireAfterAccess()))
1✔
4355
          : afterAccess;
1✔
4356
    }
4357
    @Override public Optional<FixedExpiration<K, V>> expireAfterWrite() {
4358
      if (!cache.expiresAfterWrite()) {
1✔
4359
        return Optional.empty();
1✔
4360
      }
4361
      return (afterWrite == null)
1✔
4362
          ? (afterWrite = Optional.of(new BoundedExpireAfterWrite()))
1✔
4363
          : afterWrite;
1✔
4364
    }
4365
    @Override public Optional<VarExpiration<K, V>> expireVariably() {
4366
      if (!cache.expiresVariable()) {
1✔
4367
        return Optional.empty();
1✔
4368
      }
4369
      return (variable == null)
1✔
4370
          ? (variable = Optional.of(new BoundedVarExpiration()))
1✔
4371
          : variable;
1✔
4372
    }
4373
    @Override public Optional<FixedRefresh<K, V>> refreshAfterWrite() {
4374
      if (!cache.refreshAfterWrite()) {
1✔
4375
        return Optional.empty();
1✔
4376
      }
4377
      return (refreshes == null)
1✔
4378
          ? (refreshes = Optional.of(new BoundedRefreshAfterWrite()))
1✔
4379
          : refreshes;
1✔
4380
    }
4381

4382
    final class BoundedEviction implements Eviction<K, V> {
1✔
4383
      @Override public boolean isWeighted() {
4384
        return isWeighted;
1✔
4385
      }
4386
      @Override public OptionalInt weightOf(K key) {
4387
        requireNonNull(key);
1✔
4388
        if (!isWeighted) {
1✔
4389
          return OptionalInt.empty();
1✔
4390
        }
4391
        Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1✔
4392
        if (node == null) {
1✔
4393
          return OptionalInt.empty();
1✔
4394
        }
4395
        V value = node.getValue();
1✔
4396
        if ((value == null) || cache.hasExpired(node, cache.expirationTicker().read(), value)) {
1✔
4397
          return OptionalInt.empty();
1✔
4398
        }
4399
        synchronized (node) {
1✔
4400
          return node.isAlive() ? OptionalInt.of(node.getWeight()) : OptionalInt.empty();
1✔
4401
        }
4402
      }
4403
      @Override public OptionalLong weightedSize() {
4404
        return isWeighted
1✔
4405
            ? OptionalLong.of(Math.max(0, cache.weightedSizeAcquire()))
1✔
4406
            : OptionalLong.empty();
1✔
4407
      }
4408
      @Override public long getMaximum() {
4409
        return cache.maximumAcquire();
1✔
4410
      }
4411
      @Override public void setMaximum(long maximum) {
4412
        cache.evictionLock.lock();
1✔
4413
        try {
4414
          cache.setMaximumSize(maximum);
1✔
4415
          cache.maintenance(/* ignored */ null);
1✔
4416
        } finally {
4417
          cache.evictionLock.unlock();
1✔
4418
          cache.rescheduleCleanUpIfIncomplete();
1✔
4419
        }
4420
      }
1✔
4421
      @Override public Map<K, V> coldest(int limit) {
4422
        int expectedSize = Math.min(limit, cache.size());
1✔
4423
        var limiter = new SizeLimiter<K, V>(expectedSize, limit);
1✔
4424
        return cache.evictionOrder(/* hottest= */ false, transformer, limiter);
1✔
4425
      }
4426
      @Override public Map<K, V> coldestWeighted(long weightLimit) {
4427
        var limiter = isWeighted()
1✔
4428
            ? new WeightLimiter<K, V>(weightLimit)
1✔
4429
            : new SizeLimiter<K, V>((int) Math.min(weightLimit, cache.size()), weightLimit);
1✔
4430
        return cache.evictionOrder(/* hottest= */ false, transformer, limiter);
1✔
4431
      }
4432
      @Override
4433
      public <T> T coldest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4434
        requireNonNull(mappingFunction);
1✔
4435
        return cache.evictionOrder(/* hottest= */ false, transformer, mappingFunction);
1✔
4436
      }
4437
      @Override public Map<K, V> hottest(int limit) {
4438
        int expectedSize = Math.min(limit, cache.size());
1✔
4439
        var limiter = new SizeLimiter<K, V>(expectedSize, limit);
1✔
4440
        return cache.evictionOrder(/* hottest= */ true, transformer, limiter);
1✔
4441
      }
4442
      @Override public Map<K, V> hottestWeighted(long weightLimit) {
4443
        var limiter = isWeighted()
1✔
4444
            ? new WeightLimiter<K, V>(weightLimit)
1✔
4445
            : new SizeLimiter<K, V>((int) Math.min(weightLimit, cache.size()), weightLimit);
1✔
4446
        return cache.evictionOrder(/* hottest= */ true, transformer, limiter);
1✔
4447
      }
4448
      @Override
4449
      public <T> T hottest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4450
        requireNonNull(mappingFunction);
1✔
4451
        return cache.evictionOrder(/* hottest= */ true, transformer, mappingFunction);
1✔
4452
      }
4453
    }
4454

4455
    @SuppressWarnings("PreferJavaTimeOverload")
4456
    final class BoundedExpireAfterAccess implements FixedExpiration<K, V> {
1✔
4457
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4458
        requireNonNull(key);
1✔
4459
        requireNonNull(unit);
1✔
4460
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1✔
4461
        Node<K, V> node = cache.data.get(lookupKey);
1✔
4462
        if (node == null) {
1✔
4463
          return OptionalLong.empty();
1✔
4464
        }
4465
        V value = node.getValue();
1✔
4466
        if (value == null) {
1✔
4467
          return OptionalLong.empty();
1✔
4468
        }
4469
        long now = cache.expirationTicker().read();
1✔
4470
        return cache.hasExpired(node, now, value)
1✔
4471
            ? OptionalLong.empty()
1✔
4472
            : OptionalLong.of(unit.convert(now - node.getAccessTime(), TimeUnit.NANOSECONDS));
1✔
4473
      }
4474
      @Override public long getExpiresAfter(TimeUnit unit) {
4475
        return unit.convert(cache.expiresAfterAccessNanos(), TimeUnit.NANOSECONDS);
1✔
4476
      }
4477
      @Override public void setExpiresAfter(long duration, TimeUnit unit) {
4478
        requireArgument(duration >= 0);
1!
4479
        cache.setExpiresAfterAccessNanos(unit.toNanos(duration));
1✔
4480
        cache.scheduleAfterWrite();
1✔
4481
      }
1✔
4482
      @Override public Map<K, V> oldest(int limit) {
4483
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4484
      }
4485
      @Override public <T> T oldest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4486
        return cache.expireAfterAccessOrder(/* oldest= */ true, transformer, mappingFunction);
1✔
4487
      }
4488
      @Override public Map<K, V> youngest(int limit) {
4489
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4490
      }
4491
      @Override public <T> T youngest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4492
        return cache.expireAfterAccessOrder(/* oldest= */ false, transformer, mappingFunction);
1✔
4493
      }
4494
    }
4495

4496
    @SuppressWarnings("PreferJavaTimeOverload")
4497
    final class BoundedExpireAfterWrite implements FixedExpiration<K, V> {
1✔
4498
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4499
        requireNonNull(key);
1✔
4500
        requireNonNull(unit);
1✔
4501
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1✔
4502
        Node<K, V> node = cache.data.get(lookupKey);
1✔
4503
        if (node == null) {
1✔
4504
          return OptionalLong.empty();
1✔
4505
        }
4506
        V value = node.getValue();
1✔
4507
        if (value == null) {
1✔
4508
          return OptionalLong.empty();
1✔
4509
        }
4510
        long now = cache.expirationTicker().read();
1✔
4511
        return cache.hasExpired(node, now, value)
1✔
4512
            ? OptionalLong.empty()
1✔
4513
            : OptionalLong.of(unit.convert(
1✔
4514
                (now & ~1L) - (node.getWriteTime() & ~1L), TimeUnit.NANOSECONDS));
1✔
4515
      }
4516
      @Override public long getExpiresAfter(TimeUnit unit) {
4517
        return unit.convert(cache.expiresAfterWriteNanos(), TimeUnit.NANOSECONDS);
1✔
4518
      }
4519
      @Override public void setExpiresAfter(long duration, TimeUnit unit) {
4520
        requireArgument(duration >= 0);
1✔
4521
        cache.setExpiresAfterWriteNanos(unit.toNanos(duration));
1✔
4522
        cache.scheduleAfterWrite();
1✔
4523
      }
1✔
4524
      @Override public Map<K, V> oldest(int limit) {
4525
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4526
      }
4527
      @SuppressWarnings("GuardedByChecker")
4528
      @Override public <T> T oldest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4529
        return cache.snapshot(cache.writeOrderDeque(), transformer, mappingFunction);
1✔
4530
      }
4531
      @Override public Map<K, V> youngest(int limit) {
4532
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4533
      }
4534
      @SuppressWarnings("GuardedByChecker")
4535
      @Override public <T> T youngest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4536
        return cache.snapshot(cache.writeOrderDeque()::descendingIterator,
1✔
4537
            transformer, mappingFunction);
4538
      }
4539
    }
4540

4541
    @SuppressWarnings("PreferJavaTimeOverload")
4542
    final class BoundedVarExpiration implements VarExpiration<K, V> {
1✔
4543
      @Override public OptionalLong getExpiresAfter(K key, TimeUnit unit) {
4544
        requireNonNull(key);
1✔
4545
        requireNonNull(unit);
1✔
4546
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1✔
4547
        Node<K, V> node = cache.data.get(lookupKey);
1✔
4548
        if (node == null) {
1✔
4549
          return OptionalLong.empty();
1✔
4550
        }
4551
        V value = node.getValue();
1✔
4552
        if (value == null) {
1✔
4553
          return OptionalLong.empty();
1✔
4554
        }
4555
        long now = cache.expirationTicker().read();
1✔
4556
        return cache.hasExpired(node, now, value)
1✔
4557
            ? OptionalLong.empty()
1✔
4558
            : OptionalLong.of(unit.convert(node.getVariableTime() - now, TimeUnit.NANOSECONDS));
1✔
4559
      }
4560
      @Override public void setExpiresAfter(K key, long duration, TimeUnit unit) {
4561
        requireNonNull(key);
1✔
4562
        requireNonNull(unit);
1✔
4563
        requireArgument(duration >= 0);
1✔
4564
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1✔
4565
        Node<K, V> node = cache.data.get(lookupKey);
1✔
4566
        if (node != null) {
1✔
4567
          long now;
4568
          long durationNanos = TimeUnit.NANOSECONDS.convert(duration, unit);
1✔
4569
          synchronized (node) {
1✔
4570
            now = cache.expirationTicker().read();
1✔
4571
            V value = node.getValue();
1✔
4572
            if ((value == null) || cache.isComputingAsync(value)
1✔
4573
                || cache.hasExpired(node, now, value)) {
1✔
4574
              return;
1✔
4575
            }
4576
            node.setVariableTime(now + Math.min(durationNanos, MAXIMUM_EXPIRY));
1✔
4577
          }
1✔
4578
          cache.afterRead(node, now, /* recordHit= */ false);
1✔
4579
        }
4580
      }
1✔
4581
      @Override public @Nullable V put(K key, V value, long duration, TimeUnit unit) {
4582
        requireNonNull(unit);
1✔
4583
        requireNonNull(value);
1✔
4584
        requireArgument(duration >= 0);
1✔
4585
        return cache.isAsync
1✔
4586
            ? putAsync(key, value, duration, unit)
1✔
4587
            : putSync(key, value, duration, unit, /* onlyIfAbsent= */ false);
1✔
4588
      }
4589
      @Override public @Nullable V putIfAbsent(K key, V value, long duration, TimeUnit unit) {
4590
        requireNonNull(unit);
1✔
4591
        requireNonNull(value);
1✔
4592
        requireArgument(duration >= 0);
1✔
4593
        return cache.isAsync
1✔
4594
            ? putIfAbsentAsync(key, value, duration, unit)
1✔
4595
            : putSync(key, value, duration, unit, /* onlyIfAbsent= */ true);
1✔
4596
      }
4597
      @Nullable V putSync(K key, V value, long duration, TimeUnit unit, boolean onlyIfAbsent) {
4598
        var expiry = new FixedExpireAfterWrite<K, V>(duration, unit);
1✔
4599
        return cache.put(key, value, expiry, onlyIfAbsent);
1✔
4600
      }
4601
      @SuppressWarnings("unchecked")
4602
      @Nullable V putIfAbsentAsync(K key, V value, long duration, TimeUnit unit) {
4603
        // Keep in sync with LocalAsyncCache.AsMapView#putIfAbsent(key, value)
4604
        var expiry = (Expiry<K, V>) new AsyncExpiry<>(new FixedExpireAfterWrite<>(duration, unit));
1✔
4605
        var asyncValue = (V) CompletableFuture.completedFuture(value);
1✔
4606

4607
        @Var CompletableFuture<V> priorFuture = null;
1✔
4608
        for (;;) {
4609
          priorFuture = (CompletableFuture<V>) ((priorFuture == null)
1✔
4610
              ? cache.getIfPresent(key, /* recordStats= */ false)
1✔
4611
              : cache.getIfPresentQuietly(key));
1✔
4612
          if (priorFuture != null) {
1✔
4613
            if (!priorFuture.isDone()) {
1✔
4614
              Async.getWhenSuccessful(priorFuture);
1✔
4615
              continue;
1✔
4616
            }
4617

4618
            V prior = Async.getWhenSuccessful(priorFuture);
1✔
4619
            if (prior != null) {
1✔
4620
              return prior;
1✔
4621
            }
4622
          }
4623

4624
          boolean[] added = { false };
1✔
4625
          var hints = new LocalCache.RemapHints();
1✔
4626
          var computed = (CompletableFuture<V>) cache.compute(key, (K k, @Nullable V oldValue) -> {
1✔
4627
            var oldValueFuture = (CompletableFuture<V>) oldValue;
1✔
4628
            added[0] = (oldValueFuture == null)
1✔
4629
                || (oldValueFuture.isDone() && (Async.getIfReady(oldValueFuture) == null));
1✔
4630
            if (added[0]) {
1✔
4631
              return asyncValue;
1✔
4632
            }
4633
            hints.preserveTimestamps = true;
1✔
4634
            hints.preserveRefresh = true;
1✔
4635
            return oldValue;
1✔
4636
          }, expiry, /* recordLoad= */ false, /* recordLoadFailure= */ false, hints);
4637

4638
          if (added[0]) {
1✔
4639
            return null;
1✔
4640
          } else {
4641
            V prior = Async.getWhenSuccessful(computed);
1✔
4642
            if (prior != null) {
1✔
4643
              return prior;
1✔
4644
            }
4645
          }
4646
        }
1✔
4647
      }
4648
      @SuppressWarnings("unchecked")
4649
      @Nullable V putAsync(K key, V value, long duration, TimeUnit unit) {
4650
        var expiry = (Expiry<K, V>) new AsyncExpiry<>(new FixedExpireAfterWrite<>(duration, unit));
1✔
4651
        var asyncValue = (V) CompletableFuture.completedFuture(value);
1✔
4652

4653
        var oldValueFuture = (CompletableFuture<V>) cache.put(
1✔
4654
            key, asyncValue, expiry, /* onlyIfAbsent= */ false);
4655
        return Async.getWhenSuccessful(oldValueFuture);
1✔
4656
      }
4657
      @Override public @Nullable V compute(K key,
4658
          BiFunction<? super K, ? super V, ? extends V> remappingFunction,
4659
          Duration duration) {
4660
        requireNonNull(key);
1✔
4661
        requireNonNull(duration);
1✔
4662
        requireNonNull(remappingFunction);
1✔
4663
        requireArgument(!duration.isNegative(), "duration cannot be negative: %s", duration);
1✔
4664
        var expiry = new FixedExpireAfterWrite<K, V>(
1✔
4665
            toNanosSaturated(duration), TimeUnit.NANOSECONDS);
1✔
4666

4667
        return cache.isAsync
1✔
4668
            ? computeAsync(key, remappingFunction, expiry)
1✔
4669
            : cache.compute(key, remappingFunction, expiry,
1✔
4670
                /* recordLoad= */ true, /* recordLoadFailure= */ true);
4671
      }
4672
      @Nullable V computeAsync(K key,
4673
          BiFunction<? super K, ? super V, ? extends V> remappingFunction,
4674
          Expiry<? super K, ? super V> expiry) {
4675
        // Keep in sync with LocalAsyncCache.AsMapView#compute(key, remappingFunction)
4676
        @SuppressWarnings("unchecked")
4677
        var delegate = (LocalCache<K, CompletableFuture<V>>) cache;
1✔
4678

4679
        @SuppressWarnings({"rawtypes", "unchecked", "Varifier"})
4680
        @Nullable V[] newValue = (@Nullable V[]) new Object[1];
1✔
4681
        for (;;) {
4682
          Async.getWhenSuccessful(delegate.getIfPresentQuietly(key));
1✔
4683

4684
          var hints = new LocalCache.RemapHints();
1✔
4685
          CompletableFuture<V> valueFuture = delegate.compute(
1✔
4686
              key, (K k, @Nullable CompletableFuture<V> oldValueFuture) -> {
4687
                if ((oldValueFuture != null) && !oldValueFuture.isDone()) {
1✔
4688
                  hints.preserveTimestamps = true;
1✔
4689
                  hints.preserveRefresh = true;
1✔
4690
                  return oldValueFuture;
1✔
4691
                }
4692

4693
                V oldValue = Async.getIfReady(oldValueFuture);
1✔
4694
                BiFunction<? super K, ? super V, ? extends @Nullable V> function =
1✔
4695
                    delegate.statsAware(remappingFunction,
1✔
4696
                        /* recordLoad= */ true, /* recordLoadFailure= */ true);
4697
                newValue[0] = function.apply(key, oldValue);
1✔
4698
                return (newValue[0] == null) ? null
1✔
4699
                    : CompletableFuture.completedFuture(newValue[0]);
1✔
4700
              }, new AsyncExpiry<>(expiry), /* recordLoad= */ false,
4701
              /* recordLoadFailure= */ false, hints);
4702

4703
          if (newValue[0] != null) {
1✔
4704
            return newValue[0];
1✔
4705
          } else if (valueFuture == null) {
1✔
4706
            return null;
1✔
4707
          }
4708
        }
1✔
4709
      }
4710
      @Override public Map<K, V> oldest(int limit) {
4711
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4712
      }
4713
      @Override public <T> T oldest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4714
        return cache.snapshot(cache.timerWheel(), transformer, mappingFunction);
1✔
4715
      }
4716
      @Override public Map<K, V> youngest(int limit) {
4717
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1✔
4718
      }
4719
      @Override public <T> T youngest(Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4720
        return cache.snapshot(cache.timerWheel()::descendingIterator, transformer, mappingFunction);
1✔
4721
      }
4722
    }
4723

4724
    static final class FixedExpireAfterWrite<K, V> implements Expiry<K, V> {
4725
      final long duration;
4726
      final TimeUnit unit;
4727

4728
      FixedExpireAfterWrite(long duration, TimeUnit unit) {
1✔
4729
        this.duration = duration;
1✔
4730
        this.unit = unit;
1✔
4731
      }
1✔
4732
      @Override public long expireAfterCreate(K key, V value, long currentTime) {
4733
        return unit.toNanos(duration);
1✔
4734
      }
4735
      @Override public long expireAfterUpdate(
4736
          K key, V value, long currentTime, long currentDuration) {
4737
        return unit.toNanos(duration);
1✔
4738
      }
4739
      @CanIgnoreReturnValue
4740
      @Override public long expireAfterRead(
4741
          K key, V value, long currentTime, long currentDuration) {
4742
        return currentDuration;
1✔
4743
      }
4744
    }
4745

4746
    @SuppressWarnings("PreferJavaTimeOverload")
4747
    final class BoundedRefreshAfterWrite implements FixedRefresh<K, V> {
1✔
4748
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4749
        requireNonNull(key);
1✔
4750
        requireNonNull(unit);
1✔
4751
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1✔
4752
        Node<K, V> node = cache.data.get(lookupKey);
1✔
4753
        if (node == null) {
1✔
4754
          return OptionalLong.empty();
1✔
4755
        }
4756
        V value = node.getValue();
1✔
4757
        if (value == null) {
1✔
4758
          return OptionalLong.empty();
1✔
4759
        }
4760
        long now = cache.expirationTicker().read();
1✔
4761
        return cache.hasExpired(node, now, value)
1✔
4762
            ? OptionalLong.empty()
1✔
4763
            : OptionalLong.of(unit.convert(
1✔
4764
                (now & ~1L) - (node.getWriteTime() & ~1L), TimeUnit.NANOSECONDS));
1✔
4765
      }
4766
      @Override public long getRefreshesAfter(TimeUnit unit) {
4767
        return unit.convert(cache.refreshAfterWriteNanos(), TimeUnit.NANOSECONDS);
1✔
4768
      }
4769
      @Override public void setRefreshesAfter(long duration, TimeUnit unit) {
4770
        requireNonNull(unit);
1✔
4771
        requireArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
1✔
4772
        cache.setRefreshAfterWriteNanos(unit.toNanos(duration));
1✔
4773
        cache.scheduleAfterWrite();
1✔
4774
      }
1✔
4775
    }
4776
  }
4777

4778
  /* --------------- Loading Cache --------------- */
4779

4780
  static final class BoundedLocalLoadingCache<K, V>
4781
      extends BoundedLocalManualCache<K, V> implements LocalLoadingCache<K, V> {
4782
    private static final long serialVersionUID = 1;
4783

4784
    final Function<K, @Nullable V> mappingFunction;
4785
    final @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction;
4786

4787
    BoundedLocalLoadingCache(Caffeine<K, V> builder, CacheLoader<? super K, V> loader) {
4788
      super(builder, loader);
1✔
4789
      requireNonNull(loader);
1✔
4790
      mappingFunction = newMappingFunction(loader);
1✔
4791
      bulkMappingFunction = newBulkMappingFunction(loader);
1✔
4792
    }
1✔
4793

4794
    @Override
4795
    @SuppressWarnings({"DataFlowIssue", "NullAway"})
4796
    public AsyncCacheLoader<? super K, V> cacheLoader() {
4797
      return cache.cacheLoader;
1✔
4798
    }
4799

4800
    @Override
4801
    public Function<K, @Nullable V> mappingFunction() {
4802
      return mappingFunction;
1✔
4803
    }
4804

4805
    @Override
4806
    public @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction() {
4807
      return bulkMappingFunction;
1✔
4808
    }
4809

4810
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4811
      throw new InvalidObjectException("Proxy required");
1✔
4812
    }
4813

4814
    private Object writeReplace() {
4815
      return makeSerializationProxy(cache);
1✔
4816
    }
4817
  }
4818

4819
  /* --------------- Async Cache --------------- */
4820

4821
  static final class BoundedLocalAsyncCache<K, V> implements LocalAsyncCache<K, V>, Serializable {
4822
    private static final long serialVersionUID = 1;
4823

4824
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
4825
    final boolean isWeighted;
4826

4827
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
4828
    @Nullable CacheView<K, V> cacheView;
4829
    @Nullable Policy<K, V> policy;
4830

4831
    @SuppressWarnings("unchecked")
4832
    BoundedLocalAsyncCache(Caffeine<K, V> builder) {
1✔
4833
      cache = (BoundedLocalCache<K, CompletableFuture<V>>) LocalCacheFactory
1✔
4834
          .newBoundedLocalCache(builder, /* cacheLoader= */ null, /* isAsync= */ true);
1✔
4835
      isWeighted = builder.isWeighted();
1✔
4836
    }
1✔
4837

4838
    @Override
4839
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
4840
      return cache;
1✔
4841
    }
4842

4843
    @Override
4844
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
4845
      return (mapView == null) ? (mapView = new AsyncAsMapView<>(this)) : mapView;
1✔
4846
    }
4847

4848
    @Override
4849
    public Cache<K, V> synchronous() {
4850
      return (cacheView == null) ? (cacheView = new CacheView<>(this)) : cacheView;
1✔
4851
    }
4852

4853
    @Override
4854
    public Policy<K, V> policy() {
4855
      if (policy == null) {
1✔
4856
        @SuppressWarnings("unchecked")
4857
        var castCache = (BoundedLocalCache<K, V>) cache;
1✔
4858
        Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1✔
4859
        @SuppressWarnings("unchecked")
4860
        var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1✔
4861
        policy = new BoundedPolicy<>(castCache, castTransformer, isWeighted);
1✔
4862
      }
4863
      return policy;
1✔
4864
    }
4865

4866
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4867
      throw new InvalidObjectException("Proxy required");
1✔
4868
    }
4869

4870
    private Object writeReplace() {
4871
      return makeSerializationProxy(cache);
1✔
4872
    }
4873
  }
4874

4875
  /* --------------- Async Loading Cache --------------- */
4876

4877
  static final class BoundedLocalAsyncLoadingCache<K, V>
4878
      extends LocalAsyncLoadingCache<K, V> implements Serializable {
4879
    private static final long serialVersionUID = 1;
4880

4881
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
4882
    final boolean isWeighted;
4883

4884
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
4885
    @Nullable Policy<K, V> policy;
4886

4887
    @SuppressWarnings("unchecked")
4888
    BoundedLocalAsyncLoadingCache(Caffeine<K, V> builder, AsyncCacheLoader<? super K, V> loader) {
4889
      super(loader);
1✔
4890
      isWeighted = builder.isWeighted();
1✔
4891
      cache = (BoundedLocalCache<K, CompletableFuture<V>>) LocalCacheFactory
1✔
4892
          .newBoundedLocalCache(builder, loader, /* isAsync= */ true);
1✔
4893
    }
1✔
4894

4895
    @Override
4896
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
4897
      return cache;
1✔
4898
    }
4899

4900
    @Override
4901
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
4902
      return (mapView == null) ? (mapView = new AsyncAsMapView<>(this)) : mapView;
1✔
4903
    }
4904

4905
    @Override
4906
    public Policy<K, V> policy() {
4907
      if (policy == null) {
1✔
4908
        @SuppressWarnings("unchecked")
4909
        var castCache = (BoundedLocalCache<K, V>) cache;
1✔
4910
        Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1✔
4911
        @SuppressWarnings("unchecked")
4912
        var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1✔
4913
        policy = new BoundedPolicy<>(castCache, castTransformer, isWeighted);
1✔
4914
      }
4915
      return policy;
1✔
4916
    }
4917

4918
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4919
      throw new InvalidObjectException("Proxy required");
1✔
4920
    }
4921

4922
    private Object writeReplace() {
4923
      return makeSerializationProxy(cache);
1✔
4924
    }
4925
  }
4926
}
4927

4928
/** The namespace for field padding through inheritance. */
4929
@SuppressWarnings({"IdentifierName", "MultiVariableDeclaration"})
4930
final class BLCHeader {
4931

4932
  private BLCHeader() {}
4933

4934
  @SuppressWarnings("unused")
4935
  static class PadDrainStatus {
1✔
4936
    byte p000, p001, p002, p003, p004, p005, p006, p007;
4937
    byte p008, p009, p010, p011, p012, p013, p014, p015;
4938
    byte p016, p017, p018, p019, p020, p021, p022, p023;
4939
    byte p024, p025, p026, p027, p028, p029, p030, p031;
4940
    byte p032, p033, p034, p035, p036, p037, p038, p039;
4941
    byte p040, p041, p042, p043, p044, p045, p046, p047;
4942
    byte p048, p049, p050, p051, p052, p053, p054, p055;
4943
    byte p056, p057, p058, p059, p060, p061, p062, p063;
4944
    byte p064, p065, p066, p067, p068, p069, p070, p071;
4945
    byte p072, p073, p074, p075, p076, p077, p078, p079;
4946
    byte p080, p081, p082, p083, p084, p085, p086, p087;
4947
    byte p088, p089, p090, p091, p092, p093, p094, p095;
4948
    byte p096, p097, p098, p099, p100, p101, p102, p103;
4949
    byte p104, p105, p106, p107, p108, p109, p110, p111;
4950
    byte p112, p113, p114, p115, p116, p117, p118, p119;
4951
  }
4952

4953
  /** Enforces a memory layout to avoid false sharing by padding the drain status. */
4954
  abstract static class DrainStatusRef extends PadDrainStatus {
1✔
4955
    static final VarHandle DRAIN_STATUS = fieldVarHandle(MethodHandles.lookup(),
1✔
4956
        "drainStatus", VarHandle.class, DrainStatusRef.class, int.class);
4957

4958
    /** A drain is not taking place. */
4959
    static final int IDLE = 0;
4960
    /** A drain is required due to a pending write modification. */
4961
    static final int REQUIRED = 1;
4962
    /** A drain is in progress and will transition to idle. */
4963
    static final int PROCESSING_TO_IDLE = 2;
4964
    /** A drain is in progress and will transition to required. */
4965
    static final int PROCESSING_TO_REQUIRED = 3;
4966

4967
    /** The draining status of the buffers. */
4968
    volatile int drainStatus = IDLE;
1✔
4969

4970
    /**
4971
     * Returns whether maintenance work is needed.
4972
     *
4973
     * @param delayable if draining the read buffer can be delayed
4974
     */
4975
    @SuppressWarnings("StatementSwitchToExpressionSwitch")
4976
    boolean shouldDrainBuffers(boolean delayable) {
4977
      switch (drainStatusOpaque()) {
1✔
4978
        case IDLE:
4979
          return !delayable;
1✔
4980
        case REQUIRED:
4981
          return true;
1✔
4982
        case PROCESSING_TO_IDLE:
4983
        case PROCESSING_TO_REQUIRED:
4984
          return false;
1✔
4985
        default:
4986
          throw new IllegalStateException("Invalid drain status: " + drainStatus);
1✔
4987
      }
4988
    }
4989

4990
    int drainStatusOpaque() {
4991
      return (int) DRAIN_STATUS.getOpaque(this);
1✔
4992
    }
4993

4994
    int drainStatusAcquire() {
4995
      return (int) DRAIN_STATUS.getAcquire(this);
1✔
4996
    }
4997

4998
    void setDrainStatusOpaque(int drainStatus) {
4999
      DRAIN_STATUS.setOpaque(this, drainStatus);
1✔
5000
    }
1✔
5001

5002
    void setDrainStatusRelease(int drainStatus) {
5003
      DRAIN_STATUS.setRelease(this, drainStatus);
1✔
5004
    }
1✔
5005

5006
    boolean casDrainStatus(int expect, int update) {
5007
      return DRAIN_STATUS.compareAndSet(this, expect, update);
1✔
5008
    }
5009
  }
5010
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc