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

ben-manes / caffeine / #5840

25 Oct 2026 07:14PM UTC coverage: 99.989% (-0.01%) from 100.0%
#5840

push

github

ben-manes
style polish

4881 of 4890 branches covered (99.82%)

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

1 existing line in 1 file now uncovered.

9348 of 9349 relevant lines covered (99.99%)

1.0 hits per line

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

99.96
/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.requireState;
23
import static com.github.benmanes.caffeine.cache.Caffeine.toNanosSaturated;
24
import static com.github.benmanes.caffeine.cache.Caffeine.toUnchecked;
25
import static com.github.benmanes.caffeine.cache.LocalLoadingCache.newBulkMappingFunction;
26
import static com.github.benmanes.caffeine.cache.LocalLoadingCache.newMappingFunction;
27
import static com.github.benmanes.caffeine.cache.Node.PROBATION;
28
import static com.github.benmanes.caffeine.cache.Node.PROTECTED;
29
import static com.github.benmanes.caffeine.cache.Node.WINDOW;
30
import static java.lang.invoke.ConstantBootstraps.fieldVarHandle;
31
import static java.util.Locale.US;
32
import static java.util.Objects.requireNonNull;
33
import static java.util.Spliterator.DISTINCT;
34
import static java.util.Spliterator.IMMUTABLE;
35
import static java.util.Spliterator.NONNULL;
36
import static java.util.Spliterator.ORDERED;
37

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

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

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

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

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

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

217
  /** The number of CPUs */
218
  static final int NCPU = Runtime.getRuntime().availableProcessors();
1 ✔
219
  /** The initial capacity of the write buffer. */
220
  static final int WRITE_BUFFER_MIN = 4;
221
  /** The maximum capacity of the write buffer. */
222
  static final int WRITE_BUFFER_MAX = 128 * ceilingPowerOfTwo(NCPU);
1 ✔
223
  /** The maximum weighted capacity of the map. */
224
  static final long MAXIMUM_CAPACITY = Long.MAX_VALUE - Integer.MAX_VALUE;
225
  /** The initial percent of the maximum weighted capacity dedicated to the main space. */
226
  static final double PERCENT_MAIN = 0.99d;
227
  /** The percent of the maximum weighted capacity dedicated to the main's protected space. */
228
  static final double PERCENT_MAIN_PROTECTED = 0.80d;
229
  /** The minimum popularity for allowing randomized admission. */
230
  static final int ADMIT_HASHDOS_THRESHOLD = 6;
231
  /** The maximum number of entries that can be transferred between queues. */
232
  static final int QUEUE_TRANSFER_THRESHOLD = 1_000;
233
  /** The number of expirations per policy after which a maintenance cycle defers the rest. */
234
  static final int EXPIRATION_THRESHOLD = 1_000;
235
  /** The maximum number of collected references that can be drained per maintenance cycle. */
236
  static final int REFERENCE_THRESHOLD = 1_000;
237
  /** The maximum time window between touches for expiration updates. */
238
  static final long EXPIRE_TOLERANCE = TimeUnit.SECONDS.toNanos(1);
1 ✔
239
  /** The maximum duration before an entry expires. */
240
  static final long MAXIMUM_EXPIRY = (Long.MAX_VALUE >> 1); // 150 years
241
  /** The duration to wait on the eviction lock before warning of a possible misuse. */
242
  static final long WARN_AFTER_LOCK_WAIT_NANOS = TimeUnit.SECONDS.toNanos(30);
1 ✔
243
  /** The number of retries before computing to validate the entry's integrity; pow2 modulus. */
244
  static final int MAX_PUT_SPIN_WAIT_ATTEMPTS = 1024 - 1;
245
  /** The handle for the in-flight refresh operations. */
246
  static final VarHandle REFRESHES = fieldVarHandle(MethodHandles.lookup(),
1 ✔
247
      "refreshes", VarHandle.class, BoundedLocalCache.class, ConcurrentMap.class);
248

249
  final @Nullable RemovalListener<K, V> evictionListener;
250
  final @Nullable AsyncCacheLoader<K, V> cacheLoader;
251

252
  final MpscGrowableArrayQueue<Runnable> writeBuffer;
253
  final ConcurrentHashMap<Object, Node<K, V>> data;
254
  final PerformCleanupTask drainBuffersTask;
255
  final Consumer<Node<K, V>> accessPolicy;
256
  final NodeFactory<K, V> nodeFactory;
257
  final ReentrantLock evictionLock;
258
  final Weigher<K, V> weigher;
259
  final Executor executor;
260

261
  final boolean isWeighted;
262
  final boolean isAsync;
263

264
  volatile Buffer<Node<K, V>> readBuffer;
265

266
  @Nullable Set<K> keySet;
267
  @Nullable Collection<V> values;
268
  @Nullable Set<Entry<K, V>> entrySet;
269
  volatile @Nullable ConcurrentMap<Object, CompletableFuture<?>> refreshes;
270

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

292
    if (evicts()) {
1 ✔
293
      setMaximumSize(builder.getMaximum());
1 ✔
294
    }
295
  }
1 ✔
296

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

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

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

321
  /* --------------- Shared --------------- */
322

323
  @Override
324
  public boolean isAsync() {
325
    return isAsync;
1 ✔
326
  }
327

328
  /** Returns if the node's value is currently being computed asynchronously. */
329
  final boolean isComputingAsync(@Nullable V value) {
330
    return isAsync && !Async.isReady((CompletableFuture<?>) value);
1 ✔
331
  }
332

333
  @GuardedBy("evictionLock")
334
  protected AccessOrderDeque<Node<K, V>> accessOrderWindowDeque() {
335
    throw new UnsupportedOperationException();
1 ✔
336
  }
337

338
  @GuardedBy("evictionLock")
339
  protected AccessOrderDeque<Node<K, V>> accessOrderProbationDeque() {
340
    throw new UnsupportedOperationException();
1 ✔
341
  }
342

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

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

353
  @Override
354
  public final Executor executor() {
355
    return executor;
1 ✔
356
  }
357

358
  @Override
359
  public ConcurrentMap<Object, CompletableFuture<?>> refreshes() {
360
    @Var var pending = refreshes;
1 ✔
361
    if (pending == null) {
1 ✔
362
      pending = new ConcurrentHashMap<>();
1 ✔
363
      if (!REFRESHES.compareAndSet(this, null, pending)) {
1 ✔
364
        pending = requireNonNull(refreshes);
1 ✔
365
      }
366
    }
367
    return pending;
1 ✔
368
  }
369

370
  /** Invalidate the in-flight refresh. */
371
  @SuppressWarnings("RedundantCollectionOperation")
372
  void discardRefresh(Object keyReference) {
373
    var pending = refreshes;
1 ✔
374
    if ((pending != null) && pending.containsKey(keyReference)) {
1 ✔
375
      pending.remove(keyReference);
1 ✔
376
    }
377
  }
1 ✔
378

379
  @Override
380
  public Object referenceKey(K key) {
381
    return nodeFactory.newLookupKey(key);
1 ✔
382
  }
383

384
  @Override
385
  public boolean isPendingEviction(K key) {
386
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
387
    if (node == null) {
1 ✔
388
      return false;
1 ✔
389
    }
390
    boolean expired = hasExpired(node, expirationTicker().read());
1 ✔
391
    V value = node.getValue();
1 ✔
392
    return (value == null) || (expired && !isComputingAsync(value));
1 ✔
393
  }
394

395
  /* --------------- Stats Support --------------- */
396

397
  @Override
398
  public boolean isRecordingStats() {
399
    return false;
1 ✔
400
  }
401

402
  @Override
403
  public StatsCounter statsCounter() {
404
    return StatsCounter.disabledStatsCounter();
1 ✔
405
  }
406

407
  @Override
408
  public Ticker statsTicker() {
409
    return Ticker.disabledTicker();
1 ✔
410
  }
411

412
  /* --------------- Removal Listener Support --------------- */
413

414
  @Override
415
  public @Nullable RemovalListener<K, V> removalListener() {
416
    return null;
1 ✔
417
  }
418

419
  @Override
420
  public void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause) {
421
    var removalListener = removalListener();
1 ✔
422
    if (removalListener == null) {
1 ✔
423
      return;
1 ✔
424
    }
425
    Runnable task = () -> {
1 ✔
426
      try {
427
        removalListener.onRemoval(key, value, cause);
1 ✔
428
      } catch (Throwable t) {
1 ✔
429
        if (t instanceof InterruptedException) {
1 ✔
430
          Thread.currentThread().interrupt();
1 ✔
431
        }
432
        logger.log(Level.WARNING, "Exception thrown by removal listener", t);
1 ✔
433
      }
1 ✔
434
    };
1 ✔
435
    try {
436
      executor.execute(task);
1 ✔
437
    } catch (Throwable t) {
1 ✔
438
      logger.log(Level.ERROR, "Exception thrown when submitting removal listener", t);
1 ✔
439
      task.run();
1 ✔
440
    }
1 ✔
441
  }
1 ✔
442

443
  /* --------------- Eviction Listener Support --------------- */
444

445
  void notifyEviction(@Nullable K key, @Nullable V value, RemovalCause cause) {
446
    if (evictionListener == null) {
1 ✔
447
      return;
1 ✔
448
    }
449
    try {
450
      evictionListener.onRemoval(key, value, cause);
1 ✔
451
    } catch (Throwable t) {
1 ✔
452
      if (t instanceof InterruptedException) {
1 ✔
453
        Thread.currentThread().interrupt();
1 ✔
454
      }
455
      logger.log(Level.WARNING, "Exception thrown by eviction listener", t);
1 ✔
456
    }
1 ✔
457
  }
1 ✔
458

459
  /* --------------- Reference Support --------------- */
460

461
  @Override
462
  public boolean collectKeys() {
463
    return false;
1 ✔
464
  }
465

466
  /** Returns if the values are weak or soft reference garbage collected. */
467
  protected boolean collectValues() {
468
    return false;
1 ✔
469
  }
470

471
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
472
  protected ReferenceQueue<K> keyReferenceQueue() {
473
    return null;
1 ✔
474
  }
475

476
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
477
  protected ReferenceQueue<V> valueReferenceQueue() {
478
    return null;
1 ✔
479
  }
480

481
  /* --------------- Expiration Support --------------- */
482

483
  /** Returns the {@link Pacer} used to schedule the maintenance task. */
484
  protected @Nullable Pacer pacer() {
485
    return null;
1 ✔
486
  }
487

488
  /** Returns if the cache expires entries by any of its policies. */
489
  final boolean expires() {
490
    return expiresAfterAccess() || expiresAfterWrite() || expiresVariable();
1 ✔
491
  }
492

493
  /** Returns if a read may extend when the entry expires. */
494
  final boolean expiresAfterRead() {
495
    return expiresAfterAccess() || expiresVariable();
1 ✔
496
  }
497

498
  /** Returns if the cache expires entries after a variable time threshold. */
499
  protected boolean expiresVariable() {
500
    return false;
1 ✔
501
  }
502

503
  /** Returns if the cache expires entries after an access time threshold. */
504
  protected boolean expiresAfterAccess() {
505
    return false;
1 ✔
506
  }
507

508
  /** Returns how long after the last access to an entry the map will retain that entry. */
509
  protected long expiresAfterAccessNanos() {
510
    throw new UnsupportedOperationException();
1 ✔
511
  }
512

513
  protected void setExpiresAfterAccessNanos(long expireAfterAccessNanos) {
514
    throw new UnsupportedOperationException();
1 ✔
515
  }
516

517
  /** Returns if the cache expires entries after a write time threshold. */
518
  protected boolean expiresAfterWrite() {
519
    return false;
1 ✔
520
  }
521

522
  /** Returns how long after the last write to an entry the map will retain that entry. */
523
  protected long expiresAfterWriteNanos() {
524
    throw new UnsupportedOperationException();
1 ✔
525
  }
526

527
  protected void setExpiresAfterWriteNanos(long expireAfterWriteNanos) {
528
    throw new UnsupportedOperationException();
1 ✔
529
  }
530

531
  /** Returns if the cache refreshes entries after a write time threshold. */
532
  protected boolean refreshAfterWrite() {
533
    return false;
1 ✔
534
  }
535

536
  /** Returns how long after the last write an entry becomes a candidate for refresh. */
537
  protected long refreshAfterWriteNanos() {
538
    throw new UnsupportedOperationException();
1 ✔
539
  }
540

541
  protected void setRefreshAfterWriteNanos(long refreshAfterWriteNanos) {
542
    throw new UnsupportedOperationException();
1 ✔
543
  }
544

545
  @Override
546
  @SuppressWarnings({"DataFlowIssue", "NullAway"})
547
  public Expiry<K, V> expiry() {
548
    return null;
1 ✔
549
  }
550

551
  /** Returns the {@link Ticker} used by this cache for expiration. */
552
  public Ticker expirationTicker() {
553
    return Ticker.disabledTicker();
1 ✔
554
  }
555

556
  protected TimerWheel<K, V> timerWheel() {
557
    throw new UnsupportedOperationException();
1 ✔
558
  }
559

560
  /* --------------- Eviction Support --------------- */
561

562
  /** Returns if the cache evicts entries due to a maximum size or weight threshold. */
563
  protected boolean evicts() {
564
    return false;
1 ✔
565
  }
566

567
  /** Returns if entries may be assigned different weights. */
568
  protected boolean isWeighted() {
569
    return isWeighted && (weigher != Weigher.singletonWeigher());
1 ✔
570
  }
571

572
  protected FrequencySketch frequencySketch() {
573
    throw new UnsupportedOperationException();
1 ✔
574
  }
575

576
  @GuardedBy("evictionLock")
577
  protected WindowClimber climber() {
578
    throw new UnsupportedOperationException();
1 ✔
579
  }
580

581
  /** Returns if an access to an entry can skip notifying the eviction policy. */
582
  protected boolean fastpath() {
583
    return false;
1 ✔
584
  }
585

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

591
  /** Returns the maximum weighted size. */
592
  protected long maximumAcquire() {
593
    throw new UnsupportedOperationException();
1 ✔
594
  }
595

596
  /** Returns the maximum weighted size of the window space. */
597
  protected long windowMaximum() {
598
    throw new UnsupportedOperationException();
1 ✔
599
  }
600

601
  /** Returns the maximum weighted size of the main's protected space. */
602
  protected long mainProtectedMaximum() {
603
    throw new UnsupportedOperationException();
1 ✔
604
  }
605

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

611
  @GuardedBy("evictionLock")
612
  protected void setWindowMaximum(long maximum) {
613
    throw new UnsupportedOperationException();
1 ✔
614
  }
615

616
  @GuardedBy("evictionLock")
617
  protected void setMainProtectedMaximum(long maximum) {
618
    throw new UnsupportedOperationException();
1 ✔
619
  }
620

621
  /** Returns the combined weight of the values in the cache (may be negative). */
622
  protected long weightedSize() {
623
    throw new UnsupportedOperationException();
1 ✔
624
  }
625

626
  /** Returns the combined weight of the values in the cache (may be negative). */
627
  protected long weightedSizeAcquire() {
628
    throw new UnsupportedOperationException();
1 ✔
629
  }
630

631
  /** Returns the uncorrected combined weight of the values in the window space. */
632
  protected long windowWeightedSize() {
633
    throw new UnsupportedOperationException();
1 ✔
634
  }
635

636
  /** Returns the uncorrected combined weight of the values in the main's protected space. */
637
  protected long mainProtectedWeightedSize() {
638
    throw new UnsupportedOperationException();
1 ✔
639
  }
640

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

646
  @GuardedBy("evictionLock")
647
  protected void setWindowWeightedSize(long weightedSize) {
648
    throw new UnsupportedOperationException();
1 ✔
649
  }
650

651
  @GuardedBy("evictionLock")
652
  protected void setMainProtectedWeightedSize(long weightedSize) {
653
    throw new UnsupportedOperationException();
1 ✔
654
  }
655

656
  /**
657
   * Sets the maximum weighted size of the cache. The caller may need to perform a maintenance cycle
658
   * to eagerly evicts entries until the cache shrinks to the appropriate size.
659
   */
660
  @GuardedBy("evictionLock")
661
  @SuppressWarnings({"ConstantValue", "Varifier"})
662
  void setMaximumSize(long maximum) {
663
    long max = Math.min(maximum, MAXIMUM_CAPACITY);
1 ✔
664
    if (max == maximum()) {
1 ✔
665
      return;
1 ✔
666
    }
667

668
    long window = max - (long) (PERCENT_MAIN * max);
1 ✔
669
    long mainProtected = (long) (PERCENT_MAIN_PROTECTED * (max - window));
1 ✔
670

671
    setMaximum(max);
1 ✔
672
    setWindowMaximum(window);
1 ✔
673
    setMainProtectedMaximum(mainProtected);
1 ✔
674

675
    if (climber() != null) {
1 ✔
676
      // null during the super constructor's initial sizing; the generated constructor replays this
677
      climber().resized(maximum());
1 ✔
678
    }
679

680
    if ((frequencySketch() != null) && !isWeighted() && (weightedSize() >= (max >>> 1))) {
1 ✔
681
      // Lazily initialize when close to the maximum size
682
      frequencySketch().ensureCapacity(max);
1 ✔
683
      recordReads();
1 ✔
684
    }
685
  }
1 ✔
686

687
  /** Evicts entries if the cache exceeds the maximum. */
688
  @GuardedBy("evictionLock")
689
  void evictEntries(long now) {
690
    if (!evicts()) {
1 ✔
691
      return;
1 ✔
692
    }
693
    var candidate = evictFromWindow();
1 ✔
694
    evictFromMain(candidate, now);
1 ✔
695
  }
1 ✔
696

697
  /**
698
   * Evicts entries from the window space into the main space while the window size exceeds a
699
   * maximum, transferring at most a bounded number of entries per maintenance cycle.
700
   *
701
   * @return the first candidate promoted into the probation space
702
   */
703
  @GuardedBy("evictionLock")
704
  @Nullable Node<K, V> evictFromWindow() {
705
    @Var Node<K, V> first = null;
1 ✔
706
    @Var int remaining = QUEUE_TRANSFER_THRESHOLD;
1 ✔
707
    @Var Node<K, V> node = accessOrderWindowDeque().peekFirst();
1 ✔
708
    while (windowWeightedSize() > windowMaximum()) {
1 ✔
709
      // The pending operations will adjust the size to reflect the correct weight
710
      if (node == null) {
1 ✔
711
        break;
1 ✔
712
      }
713
      if (remaining == 0) {
1 ✔
714
        // A resize can leave the window arbitrarily oversized, so the transfer is bounded per
715
        // maintenance cycle and re-armed to drain the backlog across cycles
716
        setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
717
        break;
1 ✔
718
      }
719

720
      Node<K, V> next = node.getNextInAccessOrder();
1 ✔
721
      long weight = node.getPolicyWeight();
1 ✔
722
      if (weight != 0) {
1 ✔
723
        transfer(node, weight, WINDOW, PROBATION);
1 ✔
724
        if (first == null) {
1 ✔
725
          first = node;
1 ✔
726
        }
727
        remaining--;
1 ✔
728
      }
729
      node = next;
1 ✔
730
    }
1 ✔
731

732
    return first;
1 ✔
733
  }
734

735
  /**
736
   * Evicts entries from the main space if the cache exceeds the maximum capacity. The main space
737
   * determines whether admitting an entry (coming from the window space) is preferable to retaining
738
   * the eviction policy's victim. This decision is made using a frequency filter so that the
739
   * least frequently used entry is removed.
740
   * <p>
741
   * The window space's candidates were previously promoted to the probation space at its MRU
742
   * position and the eviction policy's victim starts at the LRU position. The candidates are
743
   * evaluated in promotion order while an eviction is required, and if exhausted then additional
744
   * entries are retrieved from the window space. Likewise, if the victim selection exhausts the
745
   * probation space then additional entries are retrieved from the protected space. The queues are
746
   * consumed in LRU order and the evicted entry is the one with a lower relative frequency, where
747
   * the preference is to retain the main space's victims versus the window space's candidates on a
748
   * tie.
749
   *
750
   * @param candidate the first candidate promoted into the probation space
751
   * @param now the current time, in nanoseconds
752
   */
753
  @GuardedBy("evictionLock")
754
  void evictFromMain(@Var @Nullable Node<K, V> candidate, long now) {
755
    @Var int victimQueue = PROBATION;
1 ✔
756
    @Var int candidateQueue = PROBATION;
1 ✔
757
    @Var Node<K, V> victim = accessOrderProbationDeque().peekFirst();
1 ✔
758
    while (weightedSize() > maximum()) {
1 ✔
759
      // Search the admission window for additional candidates
760
      if ((candidate == null) && (candidateQueue == PROBATION)) {
1 ✔
761
        candidate = accessOrderWindowDeque().peekFirst();
1 ✔
762
        candidateQueue = WINDOW;
1 ✔
763
      }
764

765
      // Try evicting from the protected and window queues
766
      if ((candidate == null) && (victim == null)) {
1 ✔
767
        if (victimQueue == PROBATION) {
1 ✔
768
          victim = accessOrderProtectedDeque().peekFirst();
1 ✔
769
          victimQueue = PROTECTED;
1 ✔
770
          continue;
1 ✔
771
        } else if (victimQueue == PROTECTED) {
1 ✔
772
          victim = accessOrderWindowDeque().peekFirst();
1 ✔
773
          victimQueue = WINDOW;
1 ✔
774
          continue;
1 ✔
775
        }
776

777
        // The pending operations will adjust the size to reflect the correct weight
778
        break;
779
      }
780

781
      // Skip over entries with zero weight
782
      if ((victim != null) && (victim.getPolicyWeight() == 0)) {
1 ✔
783
        victim = victim.getNextInAccessOrder();
1 ✔
784
        continue;
1 ✔
785
      } else if ((candidate != null) && (candidate.getPolicyWeight() == 0)) {
1 ✔
786
        candidate = candidate.getNextInAccessOrder();
1 ✔
787
        continue;
1 ✔
788
      }
789

790
      // Evict immediately if only one of the entries is present
791
      if (victim == null) {
1 ✔
792
        requireNonNull(candidate);
1 ✔
793
        candidate = evictAndAdvance(candidate, now, RemovalCause.SIZE);
1 ✔
794
        continue;
1 ✔
795
      } else if (candidate == null) {
1 ✔
796
        victim = evictAndAdvance(victim, now, RemovalCause.SIZE);
1 ✔
797
        continue;
1 ✔
798
      }
799

800
      // Evict immediately if both selected the same entry
801
      if (candidate == victim) {
1 ✔
802
        victim = evictAndAdvance(victim, now, RemovalCause.SIZE);
1 ✔
803
        candidate = null;
1 ✔
804
        continue;
1 ✔
805
      }
806

807
      // Evict immediately if an entry was collected
808
      var victimKeyRef = victim.getKeyReferenceOrNull();
1 ✔
809
      var candidateKeyRef = candidate.getKeyReferenceOrNull();
1 ✔
810
      if (victimKeyRef == null) {
1 ✔
811
        victim = evictAndAdvance(victim, now, RemovalCause.COLLECTED);
1 ✔
812
        continue;
1 ✔
813
      } else if (candidateKeyRef == null) {
1 ✔
814
        candidate = evictAndAdvance(candidate, now, RemovalCause.COLLECTED);
1 ✔
815
        continue;
1 ✔
816
      }
817

818
      // Evict immediately if an entry was removed
819
      if (!victim.isAlive()) {
1 ✔
820
        victim = evictAndAdvance(victim, now, RemovalCause.SIZE);
1 ✔
821
        continue;
1 ✔
822
      } else if (!candidate.isAlive()) {
1 ✔
823
        candidate = evictAndAdvance(candidate, now, RemovalCause.SIZE);
1 ✔
824
        continue;
1 ✔
825
      }
826

827
      // Evict immediately if the candidate's weight exceeds the maximum
828
      if (candidate.getPolicyWeight() > maximum()) {
1 ✔
829
        candidate = evictAndAdvance(candidate, now, RemovalCause.SIZE);
1 ✔
830
        continue;
1 ✔
831
      }
832

833
      // Evict the entry with the lowest frequency
834
      if (admit(candidateKeyRef, victimKeyRef)) {
1 ✔
835
        victim = evictAndAdvance(victim, now, RemovalCause.SIZE);
1 ✔
836
        candidate = candidate.getNextInAccessOrder();
1 ✔
837
      } else {
838
        candidate = evictAndAdvance(candidate, now, RemovalCause.SIZE);
1 ✔
839
      }
840
    }
1 ✔
841
  }
1 ✔
842

843
  /** Evicts the entry and returns its successor, or {@code null} if it was the last. */
844
  @GuardedBy("evictionLock")
845
  @Nullable Node<K, V> evictAndAdvance(Node<K, V> node, long now, RemovalCause cause) {
846
    Node<K, V> next = node.getNextInAccessOrder();
1 ✔
847
    evictEntry(node, cause, now);
1 ✔
848
    return next;
1 ✔
849
  }
850

851
  /**
852
   * Determines if the candidate should be accepted into the main space, as determined by its
853
   * frequency relative to the victim. A small amount of randomness is used to protect against hash
854
   * collision attacks, where the victim's frequency is artificially raised so that no new entries
855
   * are admitted.
856
   *
857
   * @param candidateKeyRef the keyRef for the entry being proposed for long term retention
858
   * @param victimKeyRef the keyRef for the entry chosen by the eviction policy for replacement
859
   * @return if the candidate should be admitted and the victim ejected
860
   */
861
  @GuardedBy("evictionLock")
862
  boolean admit(Object candidateKeyRef, Object victimKeyRef) {
863
    int candidateFreq = frequencySketch().frequency(candidateKeyRef);
1 ✔
864
    int victimFreq = frequencySketch().frequency(victimKeyRef);
1 ✔
865
    if (candidateFreq > victimFreq) {
1 ✔
866
      return true;
1 ✔
867
    } else if (candidateFreq >= ADMIT_HASHDOS_THRESHOLD) {
1 ✔
868
      // The maximum frequency is 15 and halved to 7 after a reset to age the history. An attack
869
      // exploits that a hot candidate is rejected in favor of a hot victim. The threshold of a warm
870
      // candidate reduces the number of random acceptances to minimize the impact on the hit rate.
871
      int random = ThreadLocalRandom.current().nextInt();
1 ✔
872
      return ((random & 127) == 0);
1 ✔
873
    }
874
    return false;
1 ✔
875
  }
876

877
  /** Expires entries that have expired by access, write, or variable. */
878
  @GuardedBy("evictionLock")
879
  void expireEntries(long now) {
880
    expireAfterAccessEntries(now);
1 ✔
881
    expireAfterWriteEntries(now);
1 ✔
882
    expireVariableEntries(now);
1 ✔
883

884
    Pacer pacer = pacer();
1 ✔
885
    if (pacer != null) {
1 ✔
886
      long delay = getExpirationDelay(now);
1 ✔
887
      if (delay == Long.MAX_VALUE) {
1 ✔
888
        pacer.cancel();
1 ✔
889
      } else {
890
        pacer.schedule(executor, drainBuffersTask, now, delay);
1 ✔
891
      }
892
    }
893
  }
1 ✔
894

895
  /** Expires entries in the access-order queue. */
896
  @GuardedBy("evictionLock")
897
  void expireAfterAccessEntries(long now) {
898
    if (!expiresAfterAccess()) {
1 ✔
899
      return;
1 ✔
900
    }
901

902
    @Var int remaining = EXPIRATION_THRESHOLD;
1 ✔
903
    remaining = expireAfterAccessEntries(now, WINDOW, accessOrderWindowDeque(), remaining);
1 ✔
904
    if (evicts()) {
1 ✔
905
      remaining = expireAfterAccessEntries(
1 ✔
906
          now, PROBATION, accessOrderProbationDeque(), remaining);
1 ✔
907
      remaining = expireAfterAccessEntries(
1 ✔
908
          now, PROTECTED, accessOrderProtectedDeque(), remaining);
1 ✔
909
    }
910
    if (remaining == 0) {
1 ✔
911
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
912
    }
913
  }
1 ✔
914

915
  /**
916
   * Expires entries in an access-order queue, up to the {@code remaining} budget, and returns the
917
   * unused budget. When exhausted the caller re-arms maintenance to process the backlog.
918
   */
919
  @GuardedBy("evictionLock")
920
  int expireAfterAccessEntries(long now, int queueType,
921
      AccessOrderDeque<Node<K, V>> accessOrderDeque, @Var int remaining) {
922
    var head = accessOrderDeque.peekFirst();
1 ✔
923
    if (head == null) {
1 ✔
924
      return remaining;
1 ✔
925
    }
926
    long duration = expiresAfterAccessNanos();
1 ✔
927
    var last = requireNonNull(accessOrderDeque.peekLast());
1 ✔
928
    for (var node = head; (node != null) && (remaining > 0);) {
1 ✔
929
      var next = (node == last) ? null : node.getNextInAccessOrder();
1 ✔
930
      if ((now - node.getAccessTime()) < duration) {
1 ✔
931
        if (isComputingAsync(node.getValue())) {
1 ✔
932
          accessOrderDeque.moveToBack(node);
1 ✔
933
          node = next;
1 ✔
934
          continue;
1 ✔
935
        }
936
        return remaining;
1 ✔
937
      }
938
      evictEntry(node, RemovalCause.EXPIRED, now);
1 ✔
939
      remaining--;
1 ✔
940

941
      // Reentrant maintenance can unlink or move any entry, so the scan resumes from the head and
942
      // stops if the captured tail that ends the walk left the deque
943
      node = (node == last) ? null : accessOrderDeque.peekFirst();
1 ✔
944
      boolean bounded = (last.getQueueType() == queueType) && accessOrderDeque.contains(last);
1 ✔
945
      if ((node != null) && !bounded) {
1 ✔
946
        return 0;
1 ✔
947
      }
948
    }
1 ✔
949
    return remaining;
1 ✔
950
  }
951

952
  /** Expires entries on the write-order queue. */
953
  @GuardedBy("evictionLock")
954
  void expireAfterWriteEntries(long now) {
955
    if (!expiresAfterWrite()) {
1 ✔
956
      return;
1 ✔
957
    }
958

959
    var head = writeOrderDeque().peekFirst();
1 ✔
960
    if (head == null) {
1 ✔
961
      return;
1 ✔
962
    }
963
    long duration = expiresAfterWriteNanos();
1 ✔
964
    @Var int remaining = EXPIRATION_THRESHOLD;
1 ✔
965
    var last = requireNonNull(writeOrderDeque().peekLast());
1 ✔
966
    for (var node = head; (node != null) && (remaining > 0);) {
1 ✔
967
      var next = (node == last) ? null : node.getNextInWriteOrder();
1 ✔
968
      if ((now - node.getWriteTime()) < duration) {
1 ✔
969
        boolean stalePosition = ((last.getWriteTime() - node.getWriteTime()) < 0);
1 ✔
970
        if (stalePosition || isComputingAsync(node.getValue())) {
1 ✔
971
          writeOrderDeque().moveToBack(node);
1 ✔
972
          node = next;
1 ✔
973
          continue;
1 ✔
974
        }
975
        return;
1 ✔
976
      }
977
      evictEntry(node, RemovalCause.EXPIRED, now);
1 ✔
978
      remaining--;
1 ✔
979

980
      // Reentrant maintenance can unlink or move any entry, so the scan resumes from the head and
981
      // stops if the captured tail that ends the walk left the deque
982
      node = (node == last) ? null : writeOrderDeque().peekFirst();
1 ✔
983
      if ((node != null) && !writeOrderDeque().contains(last)) {
1 ✔
984
        remaining = 0;
1 ✔
985
        break;
1 ✔
986
      }
987
    }
1 ✔
988
    if (remaining == 0) {
1 ✔
989
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
990
    }
991
  }
1 ✔
992

993
  /** Expires entries in the timer wheel. */
994
  @GuardedBy("evictionLock")
995
  void expireVariableEntries(long now) {
996
    if (expiresVariable() && (timerWheel().advance(this, now, EXPIRATION_THRESHOLD) == 0)) {
1 ✔
997
      setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
998
    }
999
  }
1 ✔
1000

1001
  /** Returns the duration until the next item expires, or {@link Long#MAX_VALUE} if none. */
1002
  @GuardedBy("evictionLock")
1003
  long getExpirationDelay(long now) {
1004
    @Var long delay = Long.MAX_VALUE;
1 ✔
1005
    if (expiresAfterAccess()) {
1 ✔
1006
      @Var Node<K, V> node = accessOrderWindowDeque().peekFirst();
1 ✔
1007
      if (node != null) {
1 ✔
1008
        long age = Math.max(0, now - node.getAccessTime());
1 ✔
1009
        delay = Math.min(delay, expiresAfterAccessNanos() - age);
1 ✔
1010
      }
1011
      if (evicts()) {
1 ✔
1012
        node = accessOrderProbationDeque().peekFirst();
1 ✔
1013
        if (node != null) {
1 ✔
1014
          long age = Math.max(0, now - node.getAccessTime());
1 ✔
1015
          delay = Math.min(delay, expiresAfterAccessNanos() - age);
1 ✔
1016
        }
1017
        node = accessOrderProtectedDeque().peekFirst();
1 ✔
1018
        if (node != null) {
1 ✔
1019
          long age = Math.max(0, now - node.getAccessTime());
1 ✔
1020
          delay = Math.min(delay, expiresAfterAccessNanos() - age);
1 ✔
1021
        }
1022
      }
1023
    }
1024
    if (expiresAfterWrite()) {
1 ✔
1025
      Node<K, V> node = writeOrderDeque().peekFirst();
1 ✔
1026
      if (node != null) {
1 ✔
1027
        long age = Math.max(0, now - node.getWriteTime());
1 ✔
1028
        delay = Math.min(delay, expiresAfterWriteNanos() - age);
1 ✔
1029
      }
1030
    }
1031
    if (expiresVariable()) {
1 ✔
1032
      delay = Math.min(delay, timerWheel().getExpirationDelay(now));
1 ✔
1033
    }
1034
    return delay;
1 ✔
1035
  }
1036

1037
  /** Returns if the entry has expired. The caller must exempt an in-flight asynchronous load. */
1038
  @SuppressWarnings("ShortCircuitBoolean")
1039
  boolean hasExpired(Node<K, V> node, long now) {
1040
    if (!expires()) {
1 ✔
1041
      return false;
1 ✔
1042
    }
1043
    boolean expired =
1 ✔
1044
        (expiresAfterAccess() && (now - node.getAccessTime() >= expiresAfterAccessNanos()))
1 ✔
1045
        | (expiresAfterWrite() && (now - node.getWriteTime() >= expiresAfterWriteNanos()))
1 ✔
1046
        | (expiresVariable() && (now - node.getVariableTime() >= 0));
1 ✔
1047
    VarHandle.loadLoadFence();
1 ✔
1048
    return expired;
1 ✔
1049
  }
1050

1051
  /**
1052
   * Attempts to evict the entry based on the given removal cause. A removal may be ignored if the
1053
   * entry was updated and is no longer eligible for eviction.
1054
   *
1055
   * @param node the entry to evict
1056
   * @param cause the reason to evict
1057
   * @param now the current time, used only if expiring
1058
   * @return if the entry was evicted
1059
   */
1060
  @GuardedBy("evictionLock")
1061
  @SuppressWarnings({"GuardedByChecker", "SynchronizationOnLocalVariableOrMethodParameter"})
1062
  boolean evictEntry(Node<K, V> node, RemovalCause cause, long now) {
1063
    K key = node.getKey();
1 ✔
1064
    var ctx = new EvictContext<V>();
1 ✔
1065
    var keyReference = node.getKeyReference();
1 ✔
1066

1067
    data.computeIfPresent(keyReference, (k, n) -> {
1 ✔
1068
      if (n != node) {
1 !
UNCOV
1069
        return n;
×
1070
      }
1071
      synchronized (node) {
1 ✔
1072
        ctx.value = node.getValue();
1 ✔
1073
        boolean expired = hasExpired(node, now);
1 ✔
1074
        boolean computing = isComputingAsync(ctx.value);
1 ✔
1075
        if ((key == null) || (ctx.value == null)) {
1 ✔
1076
          ctx.cause = RemovalCause.COLLECTED;
1 ✔
1077
        } else if (cause == RemovalCause.COLLECTED) {
1 ✔
1078
          ctx.resurrect = true;
1 ✔
1079
          return node;
1 ✔
1080
        } else if (expired && !computing) {
1 ✔
1081
          ctx.cause = RemovalCause.EXPIRED;
1 ✔
1082
        } else {
1083
          ctx.cause = cause;
1 ✔
1084
        }
1085

1086
        if (ctx.cause == RemovalCause.EXPIRED) {
1 ✔
1087
          if (!expired) {
1 ✔
1088
            ctx.resurrect = true;
1 ✔
1089
            return node;
1 ✔
1090
          } else if (computing) {
1 ✔
1091
            long sentinel = (now + ASYNC_EXPIRY);
1 ✔
1092
            setVariableTime(node, sentinel);
1 ✔
1093
            setAccessTime(node, sentinel);
1 ✔
1094
            setWriteTime(node, sentinel);
1 ✔
1095
            ctx.resurrect = true;
1 ✔
1096
            return node;
1 ✔
1097
          }
1098
        } else if (ctx.cause == RemovalCause.SIZE) {
1 ✔
1099
          int weight = node.getWeight();
1 ✔
1100
          if (weight == 0) {
1 ✔
1101
            ctx.resurrect = true;
1 ✔
1102
            return node;
1 ✔
1103
          }
1104
        }
1105

1106
        notifyEviction(key, ctx.value, ctx.cause);
1 ✔
1107
        discardRefresh(keyReference);
1 ✔
1108
        ctx.removed = true;
1 ✔
1109
        node.retire();
1 ✔
1110
        return null;
1 ✔
1111
      }
1112
    });
1113

1114
    // The entry is no longer eligible for eviction
1115
    if (ctx.resurrect) {
1 ✔
1116
      return false;
1 ✔
1117
    }
1118

1119
    // If the eviction fails due to a concurrent removal of the victim, that removal may cancel out
1120
    // the addition that triggered this eviction. The victim is eagerly unlinked and the size
1121
    // decremented before the removal task so that if an eviction is still required then a new
1122
    // victim will be chosen for removal.
1123
    unlink(node);
1 ✔
1124

1125
    synchronized (node) {
1 ✔
1126
      logIfAlive(node);
1 ✔
1127
      makeDead(node);
1 ✔
1128
    }
1 ✔
1129

1130
    if (ctx.removed) {
1 ✔
1131
      var removeCause = requireNonNull(ctx.cause);
1 ✔
1132
      statsCounter().recordEviction(node.getWeight(), removeCause);
1 ✔
1133
      notifyRemoval(key, ctx.value, removeCause);
1 ✔
1134
    }
1135

1136
    return true;
1 ✔
1137
  }
1138

1139
  /** Adapts the eviction policy to towards the optimal recency / frequency configuration. */
1140
  @GuardedBy("evictionLock")
1141
  @SuppressWarnings("UnnecessaryReturnStatement")
1142
  void climb() {
1143
    if (!evicts()) {
1 ✔
1144
      return;
1 ✔
1145
    }
1146

1147
    if (frequencySketch().isNotInitialized()) {
1 ✔
1148
      climber().resetSample();
1 ✔
1149
    } else if (weightedSize() >= (maximum() >>> 1)) {
1 ✔
1150
      climber().determineAdjustment(maximum(), windowMaximum(),
1 ✔
1151
          mainProtectedMaximum(), frequencySketch().sampleSize);
1 ✔
1152
    } else {
1153
      climber().discardSample(maximum(), frequencySketch().sampleSize);
1 ✔
1154
    }
1155

1156
    demoteFromMainProtected();
1 ✔
1157
    long amount = climber().adjustment();
1 ✔
1158
    if (amount == 0) {
1 ✔
1159
      return;
1 ✔
1160
    } else if (amount > 0) {
1 ✔
1161
      increaseWindow();
1 ✔
1162
    } else {
1163
      decreaseWindow();
1 ✔
1164
    }
1165
  }
1 ✔
1166

1167
  /**
1168
   * Increases the size of the admission window by shrinking the portion allocated to the main
1169
   * space. As the main space is partitioned into probation and protected regions (80% / 20%), for
1170
   * simplicity only the protected is reduced. If the regions exceed their maximums, this may cause
1171
   * protected items to be demoted to the probation region and probation items to be demoted to the
1172
   * admission window.
1173
   */
1174
  @GuardedBy("evictionLock")
1175
  void increaseWindow() {
1176
    if (mainProtectedMaximum() == 0) {
1 ✔
1177
      return;
1 ✔
1178
    }
1179

1180
    @SuppressWarnings("MathClampLong")
1181
    @Var long quota = Math.min(climber().adjustment(), mainProtectedMaximum());
1 ✔
1182
    setMainProtectedMaximum(mainProtectedMaximum() - quota);
1 ✔
1183
    setWindowMaximum(windowMaximum() + quota);
1 ✔
1184
    demoteFromMainProtected();
1 ✔
1185

1186
    for (int i = 0; i < QUEUE_TRANSFER_THRESHOLD; i++) {
1 ✔
1187
      @Var Node<K, V> candidate = accessOrderProbationDeque().peekFirst();
1 ✔
1188
      @Var boolean probation = true;
1 ✔
1189
      if ((candidate == null) || (quota < candidate.getPolicyWeight())) {
1 ✔
1190
        candidate = accessOrderProtectedDeque().peekFirst();
1 ✔
1191
        probation = false;
1 ✔
1192
      }
1193
      if (candidate == null) {
1 ✔
1194
        break;
1 ✔
1195
      }
1196

1197
      long weight = candidate.getPolicyWeight();
1 ✔
1198
      if (quota < weight) {
1 ✔
1199
        break;
1 ✔
1200
      }
1201

1202
      quota -= weight;
1 ✔
1203
      transfer(candidate, weight, probation ? PROBATION : PROTECTED, WINDOW);
1 ✔
1204
    }
1205

1206
    setMainProtectedMaximum(mainProtectedMaximum() + quota);
1 ✔
1207
    setWindowMaximum(windowMaximum() - quota);
1 ✔
1208
    climber().carryOver(quota);
1 ✔
1209
  }
1 ✔
1210

1211
  /** Decreases the size of the admission window and increases the main's protected region. */
1212
  @GuardedBy("evictionLock")
1213
  void decreaseWindow() {
1214
    if (windowMaximum() <= 1) {
1 ✔
1215
      return;
1 ✔
1216
    }
1217

1218
    @SuppressWarnings("MathClampLong")
1219
    @Var long quota = Math.min(-climber().adjustment(), Math.max(0, windowMaximum() - 1));
1 ✔
1220
    setMainProtectedMaximum(mainProtectedMaximum() + quota);
1 ✔
1221
    setWindowMaximum(windowMaximum() - quota);
1 ✔
1222

1223
    @Var int remaining = QUEUE_TRANSFER_THRESHOLD;
1 ✔
1224
    @Var Node<K, V> candidate = accessOrderWindowDeque().peekFirst();
1 ✔
1225
    while ((candidate != null) && (remaining > 0)) {
1 ✔
1226
      Node<K, V> next = candidate.getNextInAccessOrder();
1 ✔
1227
      long weight = candidate.getPolicyWeight();
1 ✔
1228
      if (weight != 0) {
1 ✔
1229
        if (quota < weight) {
1 ✔
1230
          break;
1 ✔
1231
        }
1232
        quota -= weight;
1 ✔
1233
        transfer(candidate, weight, WINDOW, PROBATION);
1 ✔
1234
        remaining--;
1 ✔
1235
      }
1236
      candidate = next;
1 ✔
1237
    }
1 ✔
1238

1239
    setMainProtectedMaximum(mainProtectedMaximum() - quota);
1 ✔
1240
    setWindowMaximum(windowMaximum() + quota);
1 ✔
1241
    climber().carryOver(-quota);
1 ✔
1242
  }
1 ✔
1243

1244
  /** Transfers the nodes from the protected to the probation region if it exceeds the maximum. */
1245
  @GuardedBy("evictionLock")
1246
  void demoteFromMainProtected() {
1247
    long mainProtectedMaximum = mainProtectedMaximum();
1 ✔
1248
    @Var int remaining = QUEUE_TRANSFER_THRESHOLD;
1 ✔
1249
    while (mainProtectedWeightedSize() > mainProtectedMaximum) {
1 ✔
1250
      Node<K, V> demoted = accessOrderProtectedDeque().peekFirst();
1 ✔
1251
      if (demoted == null) {
1 ✔
1252
        break;
1 ✔
1253
      }
1254
      if (remaining == 0) {
1 ✔
1255
        setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
1256
        break;
1 ✔
1257
      }
1258
      transfer(demoted, demoted.getPolicyWeight(), PROTECTED, PROBATION);
1 ✔
1259
      remaining--;
1 ✔
1260
    }
1 ✔
1261
  }
1 ✔
1262

1263
  /**
1264
   * Moves the node into another region of the eviction policy, adjusting the weighted size of each
1265
   * region that tracks its own.
1266
   */
1267
  @GuardedBy("evictionLock")
1268
  void transfer(Node<K, V> node, long weight, int from, int to) {
1269
    if (from == WINDOW) {
1 ✔
1270
      setWindowWeightedSize(windowWeightedSize() - weight);
1 ✔
1271
      accessOrderWindowDeque().remove(node);
1 ✔
1272
    } else if (from == PROBATION) {
1 ✔
1273
      accessOrderProbationDeque().remove(node);
1 ✔
1274
    } else {
1275
      setMainProtectedWeightedSize(mainProtectedWeightedSize() - weight);
1 ✔
1276
      accessOrderProtectedDeque().remove(node);
1 ✔
1277
    }
1278

1279
    if (to == WINDOW) {
1 ✔
1280
      setWindowWeightedSize(windowWeightedSize() + weight);
1 ✔
1281
      accessOrderWindowDeque().offerLast(node);
1 ✔
1282
      node.makeWindow();
1 ✔
1283
    } else if (to == PROBATION) {
1 ✔
1284
      accessOrderProbationDeque().offerLast(node);
1 ✔
1285
      node.makeMainProbation();
1 ✔
1286
    } else {
1287
      setMainProtectedWeightedSize(mainProtectedWeightedSize() + weight);
1 ✔
1288
      accessOrderProtectedDeque().offerLast(node);
1 ✔
1289
      node.makeMainProtected();
1 ✔
1290
    }
1291
  }
1 ✔
1292

1293
  /**
1294
   * Performs the post-processing work required after a read.
1295
   *
1296
   * @param node the entry in the page replacement policy
1297
   * @param now the current time, in nanoseconds
1298
   * @param recordHit if the hit count should be incremented
1299
   * @return the refreshed value if immediately loaded, else null
1300
   */
1301
  @Nullable V afterRead(Node<K, V> node, long now, boolean recordHit) {
1302
    if (recordHit) {
1 ✔
1303
      statsCounter().recordHits(1);
1 ✔
1304
    }
1305

1306
    boolean delayable = (readBuffer.offer(node) != Buffer.FULL);
1 ✔
1307
    if (shouldDrainBuffers(delayable)) {
1 ✔
1308
      scheduleDrainBuffers();
1 ✔
1309
    }
1310
    return refreshIfNeeded(node, now);
1 ✔
1311
  }
1312

1313
  /** Enables the read buffer (disabled if fastpath until the frequency sketch is initialized). */
1314
  @GuardedBy("evictionLock")
1315
  void recordReads() {
1316
    if (readBuffer == Buffer.<Node<K, V>>disabled()) {
1 ✔
1317
      readBuffer = new BoundedBuffer<>();
1 ✔
1318
    }
1319
  }
1 ✔
1320

1321
  /**
1322
   * Asynchronously refreshes the entry if eligible.
1323
   *
1324
   * @param node the entry in the cache to refresh
1325
   * @param now the current time, in nanoseconds
1326
   * @return the refreshed value if immediately loaded, else null
1327
   */
1328
  @SuppressWarnings("FutureReturnValueIgnored")
1329
  @Nullable V refreshIfNeeded(Node<K, V> node, long now) {
1330
    if (!refreshAfterWrite()) {
1 ✔
1331
      return null;
1 ✔
1332
    }
1333

1334
    K key;
1335
    V oldValue;
1336
    long writeTime = node.getWriteTime();
1 ✔
1337
    long refreshWriteTime = markRefreshing(writeTime);
1 ✔
1338
    ConcurrentMap<Object, CompletableFuture<?>> refreshes;
1339
    if (((now - writeTime) > refreshAfterWriteNanos())
1 ✔
1340
        && ((key = node.getKey()) != null) && ((oldValue = node.getValue()) != null)
1 ✔
1341
        && !isComputingAsync(oldValue) && !isRefreshing(writeTime)
1 ✔
1342
        && !(refreshes = refreshes()).containsKey(node.getKeyReference())
1 ✔
1343
        && node.isAlive() && node.casWriteTime(writeTime, refreshWriteTime)) {
1 ✔
1344
      long startTime;
1345
      var keyReference = referenceKey(key);
1 ✔
1346
      CompletableFuture<? extends @Nullable V> refreshFuture;
1347
      @SuppressWarnings({"unchecked", "Varifier"})
1348
      @Nullable V[] reloading = (@Nullable V[]) new Object[1];
1 ✔
1349
      try {
1350
        // The registration is published before the loader is called, so the loader runs outside
1351
        // the refresh map's bin
1352
        var pending = new LocalLoadingCache.PendingRefresh();
1 ✔
1353
        var registered = refreshes.computeIfAbsent(keyReference, k -> {
1 ✔
1354
          if (!node.isAlive() || (node.getWriteTime() != refreshWriteTime)) {
1 ✔
1355
            return null;
1 ✔
1356
          }
1357
          // no-op if the future's completion state was modified (e.g. obtrude methods)
1358
          @SuppressWarnings("unchecked")
1359
          V value = isAsync ? Async.getIfReady((CompletableFuture<V>) oldValue) : oldValue;
1 ✔
1360
          reloading[0] = value;
1 ✔
1361
          return (value == null) ? null : pending;
1 ✔
1362
        });
1363
        if (registered != pending) {
1 ✔
1364
          return null;
1 ✔
1365
        }
1366
        try {
1367
          startTime = statsTicker().read();
1 ✔
1368
          requireNonNull(cacheLoader);
1 ✔
1369
          var refresh = cacheLoader.asyncReload(key, requireNonNull(reloading[0]), executor);
1 ✔
1370
          refreshFuture = requireNonNull(refresh, "Null future");
1 ✔
1371
        } catch (Throwable e) {
1 ✔
1372
          pending.withdraw(refreshes, keyReference, e);
1 ✔
1373
          if (e instanceof InterruptedException) {
1 ✔
1374
            Thread.currentThread().interrupt();
1 ✔
1375
          }
1376
          logger.log(Level.WARNING, "Exception thrown when submitting refresh task", e);
1 ✔
1377
          return null;
1 ✔
1378
        }
1 ✔
1379
        pending.publish(refreshes, keyReference, refreshFuture);
1 ✔
1380
      } finally {
1381
        node.casWriteTime(refreshWriteTime, writeTime);
1 ✔
1382
      }
1383

1384
      var refreshed = refreshFuture.handle((newValue, error) -> {
1 ✔
1385
        long loadTime = statsTicker().read() - startTime;
1 ✔
1386
        if (error != null) {
1 ✔
1387
          if (!(error instanceof CancellationException) && !(error instanceof TimeoutException)) {
1 ✔
1388
            logger.log(Level.WARNING, "Exception thrown during refresh", error);
1 ✔
1389
          }
1390
          refreshes.remove(keyReference, refreshFuture);
1 ✔
1391
          statsCounter().recordLoadFailure(loadTime);
1 ✔
1392
          return null;
1 ✔
1393
        }
1394

1395
        @SuppressWarnings("unchecked")
1396
        V value = (isAsync && (newValue != null)) ? (V) refreshFuture : newValue;
1 ✔
1397
        @Nullable RemovalCause[] cause = new RemovalCause[1];
1 ✔
1398
        var hints = new RemapHints();
1 ✔
1399
        hints.quietly = true;
1 ✔
1400
        V result;
1401
        try {
1402
          result = compute(key, (K k, @Nullable V currentValue) -> {
1 ✔
1403
            // Keep the refresh registered until the write clears it to avoid readers from
1404
            // prematurely scheduling another reload
1405
            boolean owned = (refreshes.get(keyReference) == refreshFuture);
1 ✔
1406
            if (currentValue == null) {
1 ✔
1407
              // If the entry is absent then drop this refresh, unless a successor owns the
1408
              // registration, and maybe notify the listener
1409
              if (value != null) {
1 ✔
1410
                cause[0] = RemovalCause.EXPLICIT;
1 ✔
1411
              }
1412
              hints.preserveRefresh = !owned;
1 ✔
1413
              return null;
1 ✔
1414
            }
1415
            if ((currentValue == oldValue) && node.isAlive()
1 ✔
1416
                && (writeTimeOf(node) == writeTime) && owned) {
1 ✔
1417
              // If the entry was not modified while in-flight (no ABA) then replace, refreshing the
1418
              // metadata even when the reloaded value is the same instance
1419
              return value;
1 ✔
1420
            }
1421
            // Otherwise the refresh is discarded. The rejection installs nothing, so the entry's
1422
            // timestamps are preserved rather than restarted at the completion time. A
1423
            // same-instance reload is not a value change, so it is not notified. When a successor
1424
            // refresh owns the registration, leave it intact so this by-key discard cannot steal
1425
            // its token.
1426
            boolean sameInstance = (currentValue == value)
1 ✔
1427
                || (isAsync && (newValue == Async.getIfReady((CompletableFuture<?>) currentValue)));
1 ✔
1428
            if ((value != null) && !sameInstance) {
1 ✔
1429
              cause[0] = RemovalCause.REPLACED;
1 ✔
1430
            }
1431
            hints.preserveTimestamps = true;
1 ✔
1432
            hints.preserveRefresh = !owned;
1 ✔
1433
            return currentValue;
1 ✔
1434
          }, expiry(), /* recordLoad= */ false, hints);
1 ✔
1435
        } catch (Throwable t) {
1 ✔
1436
          logger.log(Level.WARNING, "Exception thrown during refresh", t);
1 ✔
1437
          refreshes.remove(keyReference, refreshFuture);
1 ✔
1438
          statsCounter().recordLoadFailure(loadTime);
1 ✔
1439
          return null;
1 ✔
1440
        }
1 ✔
1441

1442
        if (cause[0] != null) {
1 ✔
1443
          notifyRemoval(key, value, cause[0]);
1 ✔
1444
        }
1445
        if (newValue == null) {
1 ✔
1446
          statsCounter().recordLoadFailure(loadTime);
1 ✔
1447
        } else {
1448
          statsCounter().recordLoadSuccess(loadTime);
1 ✔
1449
        }
1450
        return result;
1 ✔
1451
      });
1452
      return Async.getIfReady(refreshed);
1 ✔
1453
    }
1454

1455
    return null;
1 ✔
1456
  }
1457

1458
  /**
1459
   * Returns the expiration time for the entry after being created.
1460
   *
1461
   * @param key the key of the entry that was created
1462
   * @param value the value of the entry that was created
1463
   * @param expiry the calculator for the expiration time
1464
   * @param now the current time, in nanoseconds
1465
   * @return the expiration time
1466
   */
1467
  long expireAfterCreate(K key, V value, @Nullable Expiry<? super K, ? super V> expiry, long now) {
1468
    if (expiresVariable()) {
1 ✔
1469
      requireNonNull(expiry);
1 ✔
1470
      long duration = Math.max(0L, expiry.expireAfterCreate(key, value, now));
1 ✔
1471
      return expiresAt(now, duration);
1 ✔
1472
    }
1473
    return 0L;
1 ✔
1474
  }
1475

1476
  /**
1477
   * Returns the expiration time for the entry after being updated.
1478
   *
1479
   * @param node the entry in the page replacement policy
1480
   * @param key the key of the entry that was updated
1481
   * @param value the value of the entry that was updated
1482
   * @param expiry the calculator for the expiration time
1483
   * @param now the current time, in nanoseconds
1484
   * @return the expiration time
1485
   */
1486
  long expireAfterUpdate(Node<K, V> node, K key, V value,
1487
      @Nullable Expiry<? super K, ? super V> expiry, long now) {
1488
    if (expiresVariable()) {
1 ✔
1489
      requireNonNull(expiry);
1 ✔
1490
      long currentDuration = Math.max(0L, node.getVariableTime() - now);
1 ✔
1491
      long duration = Math.max(0L, expiry.expireAfterUpdate(key, value, now, currentDuration));
1 ✔
1492
      return expiresAt(now, duration);
1 ✔
1493
    }
1494
    return 0L;
1 ✔
1495
  }
1496

1497
  /**
1498
   * Returns the access time for the entry after a read.
1499
   *
1500
   * @param node the entry in the page replacement policy
1501
   * @param key the key of the entry that was read
1502
   * @param value the value of the entry that was read
1503
   * @param expiry the calculator for the expiration time
1504
   * @param now the current time, in nanoseconds
1505
   * @return the expiration time
1506
   */
1507
  long expireAfterRead(Node<K, V> node, K key, V value, Expiry<K, V> expiry, long now) {
1508
    if (expiresVariable()) {
1 ✔
1509
      long variableTime = node.getVariableTime();
1 ✔
1510
      long currentDuration = Math.max(0L, variableTime - now);
1 ✔
1511
      if (isAsync && (currentDuration > MAXIMUM_EXPIRY)) {
1 ✔
1512
        // expireAfterCreate has not yet set the duration after completion
1513
        return variableTime;
1 ✔
1514
      }
1515
      long duration = Math.max(0L, expiry.expireAfterRead(key, value, now, currentDuration));
1 ✔
1516
      return expiresAt(now, duration);
1 ✔
1517
    }
1518
    return 0L;
1 ✔
1519
  }
1520

1521
  /**
1522
   * Attempts to update the access time for the entry after a read.
1523
   *
1524
   * @param node the entry in the page replacement policy
1525
   * @param key the key of the entry that was read
1526
   * @param value the value of the entry that was read
1527
   * @param expiry the calculator for the expiration time
1528
   * @param now the current time, in nanoseconds
1529
   */
1530
  void tryExpireAfterRead(Node<K, V> node, K key, V value, Expiry<K, V> expiry, long now) {
1531
    if (!expiresVariable()) {
1 ✔
1532
      return;
1 ✔
1533
    }
1534

1535
    long variableTime = node.getVariableTime();
1 ✔
1536
    long currentDuration = Math.max(0L, variableTime - now);
1 ✔
1537
    if (isAsync && (currentDuration > MAXIMUM_EXPIRY)) {
1 ✔
1538
      // expireAfterCreate has not yet set the duration after completion
1539
      return;
1 ✔
1540
    }
1541

1542
    long tolerance = EXPIRE_TOLERANCE;
1 ✔
1543
    long duration = Math.max(0L, expiry.expireAfterRead(key, value, now, currentDuration));
1 ✔
1544
    long expirationTime = expiresAt(now, duration);
1 ✔
1545
    long extension = expirationTime - variableTime;
1 ✔
1546
    if ((extension != 0)
1 ✔
1547
        && ((duration <= tolerance) || (extension < 0) || (extension > tolerance))) {
1548
      VarHandle.loadLoadFence();
1 ✔
1549
      if (node.getValue() == value) {
1 ✔
1550
        node.casVariableTime(variableTime, expirationTime);
1 ✔
1551
      }
1552
    }
1553
  }
1 ✔
1554

1555
  void setAccessTime(Node<K, V> node, long now) {
1556
    if (!expiresAfterAccess()) {
1 ✔
1557
      return;
1 ✔
1558
    }
1559
    long tolerance = EXPIRE_TOLERANCE;
1 ✔
1560
    long accessTime = node.getAccessTime();
1 ✔
1561
    if ((expiresAfterAccessNanos() <= tolerance) || (Math.abs(now - accessTime) > tolerance)) {
1 ✔
1562
      node.setAccessTime(now);
1 ✔
1563
    }
1564
  }
1 ✔
1565

1566
  void setWriteTime(Node<K, V> node, long now) {
1567
    if (expiresAfterWrite() || refreshAfterWrite()) {
1 ✔
1568
      // The write time reserves its low bit to mark that a refresh is in flight, so a recorded time
1569
      // is always even and an age must be measured against an evenly truncated clock
1570
      node.setWriteTime(toWriteTime(now));
1 ✔
1571
    }
1572
  }
1 ✔
1573

1574
  void setVariableTime(Node<K, V> node, long expirationTime) {
1575
    if (expiresVariable()) {
1 ✔
1576
      node.setVariableTime(expirationTime);
1 ✔
1577
    }
1578
  }
1 ✔
1579

1580
  /** Returns if the entry's expiration is still deferred to its value's completion. */
1581
  boolean isExpirationDeferred(Node<K, V> node, long now) {
1582
    return expiresVariable() && ((node.getVariableTime() - now) > MAXIMUM_EXPIRY);
1 ✔
1583
  }
1584

1585
  /** Returns if the entry's write time would exceed the minimum expiration reorder threshold. */
1586
  boolean exceedsWriteTimeTolerance(Node<K, V> node, long varTime, long now) {
1587
    long variableTime = node.getVariableTime();
1 ✔
1588
    long writeTime = node.getWriteTime();
1 ✔
1589
    long tolerance = EXPIRE_TOLERANCE;
1 ✔
1590
    return
1 ✔
1591
        (expiresAfterWrite()
1 ✔
1592
            && ((expiresAfterWriteNanos() <= tolerance) || (Math.abs(now - writeTime) > tolerance)))
1 ✔
1593
        || (refreshAfterWrite()
1 ✔
1594
            && ((refreshAfterWriteNanos() <= tolerance) || (Math.abs(now - writeTime) > tolerance)))
1 ✔
1595
        || (expiresVariable() && (Math.abs(varTime - variableTime) > tolerance));
1 ✔
1596
  }
1597

1598
  /** Returns the expiration time for a duration. */
1599
  long expiresAt(long now, long duration) {
1600
    return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY));
1 ✔
1601
  }
1602

1603
  /** Returns the time to record on the entry. */
1604
  long expirationTimeFor(@Nullable V value, long now) {
1605
    return isComputingAsync(value) ? (now + ASYNC_EXPIRY) : now;
1 ✔
1606
  }
1607

1608
  /** Returns the time truncated to the write time's granularity. */
1609
  static long toWriteTime(long time) {
1610
    return (time & ~1L);
1 ✔
1611
  }
1612

1613
  /** Returns the entry's write time, with the refresh marker removed. */
1614
  static long writeTimeOf(Node<?, ?> node) {
1615
    return toWriteTime(node.getWriteTime());
1 ✔
1616
  }
1617

1618
  /** Returns if a refresh is in flight for the entry that recorded this write time. */
1619
  static boolean isRefreshing(long writeTime) {
1620
    return ((writeTime & 1L) != 0L);
1 ✔
1621
  }
1622

1623
  /** Returns the write time marked as having a refresh in flight. */
1624
  static long markRefreshing(long writeTime) {
1625
    return (writeTime | 1L);
1 ✔
1626
  }
1627

1628
  /**
1629
   * Performs the post-processing work required after a write.
1630
   *
1631
   * @param task the pending operation to be applied
1632
   */
1633
  void afterWrite(Runnable task) {
1634
    if (writeBuffer.offer(task)) {
1 ✔
1635
      scheduleAfterWrite();
1 ✔
1636
      return;
1 ✔
1637
    }
1638

1639
    // In scenarios where the writing threads cannot make progress then they attempt to provide
1640
    // assistance by performing the eviction work directly. This can resolve cases where the
1641
    // maintenance task is scheduled but not running. That might occur due to all of the executor's
1642
    // threads being busy (perhaps writing into this cache), the write rate greatly exceeds the
1643
    // consuming rate, priority inversion, or if the executor silently discarded the maintenance
1644
    // task. Unfortunately this cannot resolve when the eviction is blocked waiting on a long-
1645
    // running computation due to an eviction listener, the victim is being computed on by a writer,
1646
    // or the victim residing in the same hash bin as a computing entry. In those cases a warning is
1647
    // logged to encourage the application to decouple these computations from the map operations.
1648
    lock();
1 ✔
1649
    try {
1650
      maintenance(task);
1 ✔
1651
    } catch (RuntimeException e) {
1 ✔
1652
      logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", e);
1 ✔
1653
    } finally {
1654
      evictionLock.unlock();
1 ✔
1655
    }
1656
    rescheduleCleanUpIfIncomplete();
1 ✔
1657
  }
1 ✔
1658

1659
  /** Acquires the eviction lock. */
1660
  void lock() {
1661
    @Var long remainingNanos = WARN_AFTER_LOCK_WAIT_NANOS;
1 ✔
1662
    long end = System.nanoTime() + remainingNanos;
1 ✔
1663
    @Var boolean interrupted = false;
1 ✔
1664
    try {
1665
      for (;;) {
1666
        try {
1667
          if (evictionLock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
1 ✔
1668
            return;
1 ✔
1669
          }
1670
          logger.log(Level.WARNING, "The cache is experiencing excessive wait times for acquiring "
1 ✔
1671
              + "the eviction lock. This may indicate that a long-running computation has halted "
1672
              + "eviction when trying to remove the victim entry. Consider using AsyncCache to "
1673
              + "decouple the computation from the map operation.", new TimeoutException());
1674
          evictionLock.lock();
1 ✔
1675
          return;
1 ✔
1676
        } catch (InterruptedException e) {
1 ✔
1677
          remainingNanos = end - System.nanoTime();
1 ✔
1678
          interrupted = true;
1 ✔
1679
        }
1 ✔
1680
      }
1681
    } finally {
1682
      if (interrupted) {
1 ✔
1683
        Thread.currentThread().interrupt();
1 ✔
1684
      }
1685
    }
1686
  }
1687

1688
  /**
1689
   * Conditionally schedules the asynchronous maintenance task after a write operation. If the
1690
   * task status was IDLE or REQUIRED then the maintenance task is scheduled immediately. If it
1691
   * is already processing then it is set to transition to REQUIRED upon completion so that a new
1692
   * execution is triggered by the next operation.
1693
   */
1694
  void scheduleAfterWrite() {
1695
    @Var int drainStatus = drainStatusOpaque();
1 ✔
1696
    for (;;) {
1697
      switch (drainStatus) {
1 ✔
1698
        case IDLE:
1699
          if (casDrainStatus(IDLE, REQUIRED)) {
1 ✔
1700
            scheduleDrainBuffers();
1 ✔
1701
            return;
1 ✔
1702
          }
1703
          drainStatus = drainStatusAcquire();
1 ✔
1704
          continue;
1 ✔
1705
        case REQUIRED:
1706
          scheduleDrainBuffers();
1 ✔
1707
          return;
1 ✔
1708
        case PROCESSING_TO_IDLE:
1709
          if (casDrainStatus(PROCESSING_TO_IDLE, PROCESSING_TO_REQUIRED)) {
1 ✔
1710
            return;
1 ✔
1711
          }
1712
          drainStatus = drainStatusAcquire();
1 ✔
1713
          continue;
1 ✔
1714
        case PROCESSING_TO_REQUIRED:
1715
          return;
1 ✔
1716
        default:
1717
          throw new IllegalStateException("Invalid drain status: " + drainStatus);
1 ✔
1718
      }
1719
    }
1720
  }
1721

1722
  /**
1723
   * Attempts to schedule an asynchronous task to apply the pending operations to the page
1724
   * replacement policy. If the executor rejects the task then it is run directly.
1725
   */
1726
  void scheduleDrainBuffers() {
1727
    if (drainStatusOpaque() >= PROCESSING_TO_IDLE) {
1 ✔
1728
      return;
1 ✔
1729
    }
1730
    if (evictionLock.tryLock()) {
1 ✔
1731
      try {
1732
        int drainStatus = drainStatusOpaque();
1 ✔
1733
        if (drainStatus >= PROCESSING_TO_IDLE) {
1 ✔
1734
          return;
1 ✔
1735
        }
1736
        setDrainStatusRelease(PROCESSING_TO_IDLE);
1 ✔
1737
        executor.execute(drainBuffersTask);
1 ✔
1738
      } catch (Throwable t) {
1 ✔
1739
        logger.log(Level.WARNING, "Exception thrown when submitting maintenance task", t);
1 ✔
1740
        maintenance(/* ignored */ null);
1 ✔
1741
      } finally {
1742
        evictionLock.unlock();
1 ✔
1743
      }
1744
    }
1745
  }
1 ✔
1746

1747
  /** Returns whether a thread waits for the eviction lock and this thread does not hold it. */
1748
  boolean isEvictionLockAwaited() {
1749
    return !evictionLock.isHeldByCurrentThread() && evictionLock.hasQueuedThreads();
1 ✔
1750
  }
1751

1752
  @Override
1753
  public void cleanUp() {
1754
    try {
1755
      performCleanUp(/* ignored */ null);
1 ✔
1756
    } catch (RuntimeException e) {
1 ✔
1757
      logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", e);
1 ✔
1758
    }
1 ✔
1759
  }
1 ✔
1760

1761
  /**
1762
   * Performs the maintenance work, blocking until the lock is acquired.
1763
   *
1764
   * @param task an additional pending task to run, or {@code null} if not present
1765
   */
1766
  void performCleanUp(@Nullable Runnable task) {
1767
    evictionLock.lock();
1 ✔
1768
    try {
1769
      maintenance(task);
1 ✔
1770
    } finally {
1771
      evictionLock.unlock();
1 ✔
1772
    }
1773
    rescheduleCleanUpIfIncomplete();
1 ✔
1774
  }
1 ✔
1775

1776
  /**
1777
   * If there remains pending operations that were not handled by the prior clean up then try to
1778
   * schedule an asynchronous maintenance task. This may occur due to a concurrent write after the
1779
   * maintenance work had started or if the amortized threshold of work per clean up was reached.
1780
   */
1781
  @SuppressWarnings("resource")
1782
  void rescheduleCleanUpIfIncomplete() {
1783
    if (drainStatusOpaque() != REQUIRED) {
1 ✔
1784
      return;
1 ✔
1785
    }
1786

1787
    // An immediate scheduling cannot be performed on a custom executor because it may use a
1788
    // caller-runs policy. This could cause the caller's penalty to exceed the amortized threshold,
1789
    // e.g. repeated concurrent writes could result in a retry loop.
1790
    if (executor == ForkJoinPool.commonPool()) {
1 ✔
1791
      scheduleDrainBuffers();
1 ✔
1792
      return;
1 ✔
1793
    }
1794

1795
    // If a scheduler was configured then the maintenance can be deferred onto the custom executor
1796
    // and run in the near future. Otherwise, it will be handled due to other cache activity.
1797
    var pacer = pacer();
1 ✔
1798
    if ((pacer != null) && !pacer.isScheduled() && evictionLock.tryLock()) {
1 ✔
1799
      try {
1800
        if ((drainStatusOpaque() == REQUIRED) && !pacer.isScheduled()) {
1 ✔
1801
          pacer.schedule(executor, drainBuffersTask, expirationTicker().read(), Pacer.TOLERANCE);
1 ✔
1802
        }
1803
      } finally {
1804
        evictionLock.unlock();
1 ✔
1805
      }
1806
    }
1807
  }
1 ✔
1808

1809
  /**
1810
   * Performs the pending maintenance work and sets the state flags during processing to avoid
1811
   * excess scheduling attempts. The read buffer, write buffer, and reference queues are drained,
1812
   * followed by expiration, and size-based eviction.
1813
   *
1814
   * @param task an additional pending task to run, or {@code null} if not present
1815
   */
1816
  @GuardedBy("evictionLock")
1817
  void maintenance(@Nullable Runnable task) {
1818
    setDrainStatusRelease(PROCESSING_TO_IDLE);
1 ✔
1819

1820
    try {
1821
      try {
1822
        drainReadBuffer();
1 ✔
1823
        drainWriteBuffer();
1 ✔
1824
      } finally {
1825
        if (task != null) {
1 ✔
1826
          task.run();
1 ✔
1827
        }
1828
      }
1829

1830
      drainKeyReferences();
1 ✔
1831
      drainValueReferences();
1 ✔
1832

1833
      long now = expirationTicker().read();
1 ✔
1834
      expireEntries(now);
1 ✔
1835
      evictEntries(now);
1 ✔
1836

1837
      climb();
1 ✔
1838
    } finally {
1839
      if ((drainStatusOpaque() != PROCESSING_TO_IDLE)
1 ✔
1840
          || !casDrainStatus(PROCESSING_TO_IDLE, IDLE)) {
1 ✔
1841
        setDrainStatusOpaque(REQUIRED);
1 ✔
1842
      }
1843
    }
1844
  }
1 ✔
1845

1846
  /** Drains the weak key references queue. */
1847
  @GuardedBy("evictionLock")
1848
  void drainKeyReferences() {
1849
    if (!collectKeys()) {
1 ✔
1850
      return;
1 ✔
1851
    }
1852
    for (int i = 0; i <= REFERENCE_THRESHOLD; i++) {
1 ✔
1853
      var keyRef = keyReferenceQueue().poll();
1 ✔
1854
      if (keyRef == null) {
1 ✔
1855
        return;
1 ✔
1856
      }
1857
      Node<K, V> node = data.get(keyRef);
1 ✔
1858
      if (node != null) {
1 ✔
1859
        evictEntry(node, RemovalCause.COLLECTED, 0L);
1 ✔
1860
      }
1861
    }
1862
    setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
1863
  }
1 ✔
1864

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

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

1892
  /**
1893
   * Updates the node's location in the page replacement policy and credits the access.
1894
   * <p>
1895
   * A quiet access reorders but does not record the usage with the admission filter or the adaptive
1896
   * climber's sample, as an asynchronous cache's load completion finalizes the entry's weight
1897
   * rather than conveying a usage; counting it once per load skews the admission frequencies and
1898
   * misattributes window hits.
1899
   */
1900
  @GuardedBy("evictionLock")
1901
  void onAccess(Node<K, V> node, Access access) {
1902
    if (evicts()) {
1 ✔
1903
      var keyRef = node.getKeyReferenceOrNull();
1 ✔
1904
      if ((keyRef == null) || !node.isAlive()) {
1 ✔
1905
        return;
1 ✔
1906
      }
1907
      if (access.recordsUsage()) {
1 ✔
1908
        frequencySketch().increment(keyRef);
1 ✔
1909
      }
1910
      boolean inWindow = node.inWindow();
1 ✔
1911
      boolean inProbation = !inWindow && node.inMainProbation();
1 ✔
1912
      if (inWindow) {
1 ✔
1913
        reorder(accessOrderWindowDeque(), node);
1 ✔
1914
      } else if (inProbation) {
1 ✔
1915
        reorderProbation(node);
1 ✔
1916
      } else {
1917
        reorder(accessOrderProtectedDeque(), node);
1 ✔
1918
      }
1919
      if (access.recordsHit() && (node.getPolicyWeight() != 0)) {
1 ✔
1920
        // a zero-weight entry (an in-flight async load, a pinned entry) earns hits with no
1921
        // capacity, so it must not steer the sizing; the sketch still observes the key
1922
        climber().recordHit(inWindow, inProbation);
1 ✔
1923
      }
1924
    } else if (expiresAfterAccess()) {
1 ✔
1925
      reorder(accessOrderWindowDeque(), node);
1 ✔
1926
    }
1927
    if (expiresVariable()) {
1 ✔
1928
      timerWheel().reschedule(node);
1 ✔
1929
    }
1930
  }
1 ✔
1931

1932
  /** Promote the node from probation to protected on an access. */
1933
  @GuardedBy("evictionLock")
1934
  void reorderProbation(Node<K, V> node) {
1935
    if (!accessOrderProbationDeque().contains(node)) {
1 ✔
1936
      // Ignore stale accesses for an entry that is no longer present
1937
      return;
1 ✔
1938
    } else if (node.getPolicyWeight() > mainProtectedMaximum()) {
1 ✔
1939
      reorder(accessOrderProbationDeque(), node);
1 ✔
1940
      return;
1 ✔
1941
    }
1942

1943
    // If the protected space exceeds its maximum, the LRU items are demoted to the probation space.
1944
    // This is deferred to the adaption phase at the end of the maintenance cycle.
1945
    transfer(node, node.getPolicyWeight(), PROBATION, PROTECTED);
1 ✔
1946
  }
1 ✔
1947

1948
  /** Updates the node's location in the policy's deque, unless it is no longer linked. */
1949
  static <K, V> void reorder(LinkedDeque<Node<K, V>> deque, Node<K, V> node) {
1950
    // An entry may be scheduled for reordering despite having been removed. This can occur when the
1951
    // entry was concurrently read while a writer was removing it. If the entry is no longer linked
1952
    // then it does not need to be processed.
1953
    if (deque.contains(node)) {
1 ✔
1954
      deque.moveToBack(node);
1 ✔
1955
    }
1956
  }
1 ✔
1957

1958
  /** Drains the write buffer. */
1959
  @GuardedBy("evictionLock")
1960
  void drainWriteBuffer() {
1961
    for (int i = 0; i <= WRITE_BUFFER_MAX; i++) {
1 ✔
1962
      Runnable task = writeBuffer.relaxedPoll();
1 ✔
1963
      if (task == null) {
1 ✔
1964
        return;
1 ✔
1965
      }
1966
      task.run();
1 ✔
1967
    }
1968
    setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
1969
  }
1 ✔
1970

1971
  /** Removes the node from the policy's queues. */
1972
  @GuardedBy("evictionLock")
1973
  void unlink(Node<K, V> node) {
1974
    if (node.inWindow() && (evicts() || expiresAfterAccess())) {
1 ✔
1975
      accessOrderWindowDeque().remove(node);
1 ✔
1976
    } else if (evicts()) {
1 ✔
1977
      if (node.inMainProbation()) {
1 ✔
1978
        accessOrderProbationDeque().remove(node);
1 ✔
1979
      } else {
1980
        accessOrderProtectedDeque().remove(node);
1 ✔
1981
      }
1982
    }
1983
    if (expiresAfterWrite()) {
1 ✔
1984
      writeOrderDeque().remove(node);
1 ✔
1985
    } else if (expiresVariable()) {
1 ✔
1986
      timerWheel().deschedule(node);
1 ✔
1987
    }
1988
  }
1 ✔
1989

1990
  /**
1991
   * Atomically transitions the node to the <code>dead</code> state and decrements the
1992
   * <code>weightedSize</code>.
1993
   *
1994
   * @param node the entry in the page replacement policy
1995
   */
1996
  @GuardedBy("evictionLock")
1997
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
1998
  void makeDead(Node<K, V> node) {
1999
    synchronized (node) {
1 ✔
2000
      if (node.isDead()) {
1 ✔
2001
        return;
1 ✔
2002
      }
2003
      if (evicts()) {
1 ✔
2004
        // The node's policy weight may be out of sync due to a pending update waiting to be
2005
        // processed. At this point the node's weight is finalized, so the weight can be safely
2006
        // taken from the node's perspective and the sizes will be adjusted correctly.
2007
        if (node.inWindow()) {
1 ✔
2008
          setWindowWeightedSize(windowWeightedSize() - node.getWeight());
1 ✔
2009
        } else if (node.inMainProtected()) {
1 ✔
2010
          setMainProtectedWeightedSize(mainProtectedWeightedSize() - node.getWeight());
1 ✔
2011
        }
2012
        setWeightedSize(weightedSize() - node.getWeight());
1 ✔
2013
      }
2014
      node.die();
1 ✔
2015
    }
1 ✔
2016
  }
1 ✔
2017

2018
  /** Adds the node to the page replacement policy. */
2019
  final class AddTask implements Runnable {
2020
    final Node<K, V> node;
2021
    final int weight;
2022

2023
    AddTask(Node<K, V> node, int weight) {
1 ✔
2024
      this.weight = weight;
1 ✔
2025
      this.node = node;
1 ✔
2026
    }
1 ✔
2027

2028
    @Override
2029
    @GuardedBy("evictionLock")
2030
    public void run() {
2031
      if (evicts()) {
1 ✔
2032
        setWeightedSize(weightedSize() + weight);
1 ✔
2033
        setWindowWeightedSize(windowWeightedSize() + weight);
1 ✔
2034
        node.setPolicyWeight(node.getPolicyWeight() + weight);
1 ✔
2035

2036
        long maximum = maximum();
1 ✔
2037
        if (weightedSize() >= (maximum >>> 1)) {
1 ✔
2038
          if (weightedSize() > MAXIMUM_CAPACITY) {
1 ✔
2039
            evictEntries(expirationTicker().read());
1 ✔
2040
          } else {
2041
            // Lazily initialize when close to the maximum
2042
            long capacity = isWeighted() ? data.mappingCount() : maximum;
1 ✔
2043
            frequencySketch().ensureCapacity(capacity);
1 ✔
2044
            recordReads();
1 ✔
2045
          }
2046
        }
2047

2048
        climber().recordMiss();
1 ✔
2049
      }
2050

2051
      // ignore out-of-order write operations
2052
      boolean isAlive;
2053
      synchronized (node) {
1 ✔
2054
        isAlive = node.isAlive();
1 ✔
2055
      }
1 ✔
2056
      if (isAlive) {
1 ✔
2057
        if (expiresAfterWrite()) {
1 ✔
2058
          writeOrderDeque().offerLast(node);
1 ✔
2059
        }
2060
        if (expiresVariable()) {
1 ✔
2061
          timerWheel().schedule(node);
1 ✔
2062
        }
2063
        if (evicts()) {
1 ✔
2064
          var keyRef = node.getKeyReferenceOrNull();
1 ✔
2065
          if ((keyRef != null) && node.isAlive()) {
1 ✔
2066
            frequencySketch().increment(keyRef);
1 ✔
2067
          }
2068
          if (weight > windowMaximum()) {
1 ✔
2069
            accessOrderWindowDeque().offerFirst(node);
1 ✔
2070
          } else {
2071
            accessOrderWindowDeque().offerLast(node);
1 ✔
2072
          }
2073
          if (weight > maximum()) {
1 ✔
2074
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1 ✔
2075
          }
2076
        } else if (expiresAfterAccess()) {
1 ✔
2077
          accessOrderWindowDeque().offerLast(node);
1 ✔
2078
        }
2079
      }
2080
    }
1 ✔
2081
  }
2082

2083
  /** Removes a node from the page replacement policy. */
2084
  final class RemovalTask implements Runnable {
2085
    final Node<K, V> node;
2086

2087
    RemovalTask(Node<K, V> node) {
1 ✔
2088
      this.node = node;
1 ✔
2089
    }
1 ✔
2090

2091
    @Override
2092
    @GuardedBy("evictionLock")
2093
    public void run() {
2094
      // add may not have been processed yet
2095
      unlink(node);
1 ✔
2096
      makeDead(node);
1 ✔
2097
    }
1 ✔
2098
  }
2099

2100
  /** Updates the weighted size. */
2101
  final class UpdateTask implements Runnable {
2102
    final int weightDifference;
2103
    final Node<K, V> node;
2104
    final Access access;
2105

2106
    public UpdateTask(Node<K, V> node, int weightDifference) {
2107
      this(node, weightDifference, Access.HIT);
1 ✔
2108
    }
1 ✔
2109

2110
    public UpdateTask(Node<K, V> node, int weightDifference, Access access) {
1 ✔
2111
      this.weightDifference = weightDifference;
1 ✔
2112
      this.access = access;
1 ✔
2113
      this.node = node;
1 ✔
2114
    }
1 ✔
2115

2116
    @Override
2117
    @GuardedBy("evictionLock")
2118
    public void run() {
2119
      if (expiresAfterWrite()) {
1 ✔
2120
        reorder(writeOrderDeque(), node);
1 ✔
2121
      } else if (expiresVariable()) {
1 ✔
2122
        timerWheel().reschedule(node);
1 ✔
2123
      }
2124
      if (evicts()) {
1 ✔
2125
        if (access.recordsMiss()) {
1 ✔
2126
          climber().recordMiss();
1 ✔
2127
        }
2128
        long oldWeightedSize = node.getPolicyWeight();
1 ✔
2129
        node.setPolicyWeight(oldWeightedSize + weightDifference);
1 ✔
2130
        if (node.inWindow()) {
1 ✔
2131
          setWindowWeightedSize(windowWeightedSize() + weightDifference);
1 ✔
2132
          if (node.getPolicyWeight() > maximum()) {
1 ✔
2133
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1 ✔
2134
          } else if (node.getPolicyWeight() <= windowMaximum()) {
1 ✔
2135
            onAccess(node, access);
1 ✔
2136
          } else if (accessOrderWindowDeque().contains(node)) {
1 ✔
2137
            accessOrderWindowDeque().moveToFront(node);
1 ✔
2138
          }
2139
        } else if (node.inMainProbation()) {
1 ✔
2140
          if (node.getPolicyWeight() <= maximum()) {
1 ✔
2141
            onAccess(node, access);
1 ✔
2142
          } else {
2143
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1 ✔
2144
          }
2145
        } else {
2146
          setMainProtectedWeightedSize(mainProtectedWeightedSize() + weightDifference);
1 ✔
2147
          if (node.getPolicyWeight() <= maximum()) {
1 ✔
2148
            onAccess(node, access);
1 ✔
2149
          } else {
2150
            evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1 ✔
2151
          }
2152
        }
2153

2154
        setWeightedSize(weightedSize() + weightDifference);
1 ✔
2155
        if (weightedSize() > MAXIMUM_CAPACITY) {
1 ✔
2156
          evictEntries(expirationTicker().read());
1 ✔
2157
        }
2158
      } else if (expiresAfterAccess()) {
1 ✔
2159
        onAccess(node, access);
1 ✔
2160
      }
2161
    }
1 ✔
2162
  }
2163

2164
  /** What an access records beyond the reorder. */
2165
  enum Access {
1 ✔
2166
    HIT(/* usage= */ true, /* hit= */ true, /* miss= */ false),
1 ✔
2167
    RELOAD(/* usage= */ true, /* hit= */ false, /* miss= */ true),
1 ✔
2168
    QUIET(/* usage= */ false, /* hit= */ false, /* miss= */ false);
1 ✔
2169

2170
    private final boolean hit;
2171
    private final boolean miss;
2172
    private final boolean usage;
2173

2174
    Access(boolean usage, boolean hit, boolean miss) {
1 ✔
2175
      this.usage = usage;
1 ✔
2176
      this.hit = hit;
1 ✔
2177
      this.miss = miss;
1 ✔
2178
    }
1 ✔
2179

2180
    /** Returns whether the admission filter observes the key. */
2181
    boolean recordsUsage() {
2182
      return usage;
1 ✔
2183
    }
2184

2185
    /** Returns whether the climber's sample earns a hit. */
2186
    boolean recordsHit() {
2187
      return hit;
1 ✔
2188
    }
2189

2190
    /** Returns whether the climber's sample takes the miss an insertion would have recorded. */
2191
    boolean recordsMiss() {
2192
      return miss;
1 ✔
2193
    }
2194
  }
2195

2196
  /* --------------- Concurrent Map Support --------------- */
2197

2198
  @Override
2199
  public boolean isEmpty() {
2200
    return data.isEmpty();
1 ✔
2201
  }
2202

2203
  @Override
2204
  public int size() {
2205
    return data.size();
1 ✔
2206
  }
2207

2208
  @Override
2209
  public long estimatedSize() {
2210
    return data.mappingCount();
1 ✔
2211
  }
2212

2213
  @Override
2214
  public void clear() {
2215
    // Discard all pending refreshes
2216
    var pending = refreshes;
1 ✔
2217
    if (pending != null) {
1 ✔
2218
      pending.clear();
1 ✔
2219
    }
2220

2221
    Deque<Node<K, V>> entries;
2222
    evictionLock.lock();
1 ✔
2223
    try {
2224
      // Discard all pending reads
2225
      readBuffer.drainTo(e -> {});
1 ✔
2226

2227
      // Apply the pending writes
2228
      for (var task = writeBuffer.relaxedPoll(); task != null; task = writeBuffer.relaxedPoll()) {
1 ✔
2229
        task.run();
1 ✔
2230
      }
2231

2232
      // Cancel the scheduled cleanup
2233
      Pacer pacer = pacer();
1 ✔
2234
      if (pacer != null) {
1 ✔
2235
        pacer.cancel();
1 ✔
2236
      }
2237

2238
      // Discard all entries, falling back to one-by-one to avoid excessive lock hold times
2239
      long now = expirationTicker().read();
1 ✔
2240
      int threshold = (WRITE_BUFFER_MAX / 2);
1 ✔
2241
      entries = new ArrayDeque<>(data.values());
1 ✔
2242
      while (writeBuffer.size() < threshold) {
1 ✔
2243
        var node = entries.pollFirst();
1 ✔
2244
        if (node == null) {
1 ✔
2245
          break;
1 ✔
2246
        }
2247
        removeNode(node, now);
1 ✔
2248
      }
1 ✔
2249

2250
      // A submitted task that ran while this thread waited for the lock deferred to it
2251
      if (drainStatusOpaque() >= PROCESSING_TO_IDLE) {
1 ✔
2252
        setDrainStatusRelease(REQUIRED);
1 ✔
2253
      }
2254
    } finally {
2255
      evictionLock.unlock();
1 ✔
2256
    }
2257

2258
    // Remove any stragglers if released early to more aggressively flush incoming writes
2259
    @Var boolean cleanUp = false;
1 ✔
2260
    for (var node : entries) {
1 ✔
2261
      var key = node.getKey();
1 ✔
2262
      if (key == null) {
1 ✔
2263
        cleanUp = true;
1 ✔
2264
      } else {
2265
        remove(key);
1 ✔
2266
      }
2267
    }
1 ✔
2268
    if (collectKeys() && cleanUp) {
1 ✔
2269
      cleanUp();
1 ✔
2270
    } else {
2271
      rescheduleCleanUpIfIncomplete();
1 ✔
2272
    }
2273
  }
1 ✔
2274

2275
  @GuardedBy("evictionLock")
2276
  @SuppressWarnings({"GuardedByChecker", "SynchronizationOnLocalVariableOrMethodParameter"})
2277
  void removeNode(Node<K, V> node, long now) {
2278
    K key = node.getKey();
1 ✔
2279
    var ctx = new EvictContext<V>();
1 ✔
2280
    var keyReference = node.getKeyReference();
1 ✔
2281

2282
    data.computeIfPresent(keyReference, (k, n) -> {
1 ✔
2283
      if (n != node) {
1 ✔
2284
        return n;
1 ✔
2285
      }
2286
      synchronized (node) {
1 ✔
2287
        ctx.value = node.getValue();
1 ✔
2288
        ctx.oldWeight = node.getWeight();
1 ✔
2289

2290
        if ((key == null) || (ctx.value == null)) {
1 ✔
2291
          ctx.cause = RemovalCause.COLLECTED;
1 ✔
2292
        } else if (hasExpired(node, now) && !isComputingAsync(ctx.value)) {
1 ✔
2293
          ctx.cause = RemovalCause.EXPIRED;
1 ✔
2294
        } else {
2295
          ctx.cause = RemovalCause.EXPLICIT;
1 ✔
2296
        }
2297

2298
        if (ctx.cause.wasEvicted()) {
1 ✔
2299
          notifyEviction(key, ctx.value, ctx.cause);
1 ✔
2300
        }
2301

2302
        discardRefresh(k);
1 ✔
2303
        node.retire();
1 ✔
2304
        return null;
1 ✔
2305
      }
2306
    });
2307

2308
    unlink(node);
1 ✔
2309

2310
    synchronized (node) {
1 ✔
2311
      logIfAlive(node);
1 ✔
2312
      makeDead(node);
1 ✔
2313
    }
1 ✔
2314

2315
    if (ctx.cause != null) {
1 ✔
2316
      if (ctx.cause.wasEvicted()) {
1 ✔
2317
        statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1 ✔
2318
      }
2319
      notifyRemoval(key, ctx.value, ctx.cause);
1 ✔
2320
    }
2321
  }
1 ✔
2322

2323
  @Override
2324
  public boolean containsKey(@Nullable Object key) {
2325
    requireNonNull(key);
1 ✔
2326

2327
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
2328
    if (node == null) {
1 ✔
2329
      return false;
1 ✔
2330
    }
2331
    boolean expired = hasExpired(node, expirationTicker().read());
1 ✔
2332
    V value = node.getValue();
1 ✔
2333
    if ((value == null) || (expired && !isComputingAsync(value))) {
1 ✔
2334
      scheduleDrainBuffers();
1 ✔
2335
      return false;
1 ✔
2336
    }
2337
    return true;
1 ✔
2338
  }
2339

2340
  @Override
2341
  public boolean containsValue(@Nullable Object value) {
2342
    requireNonNull(value);
1 ✔
2343

2344
    long now = expirationTicker().read();
1 ✔
2345
    for (Node<K, V> node : data.values()) {
1 ✔
2346
      boolean expired = hasExpired(node, now);
1 ✔
2347
      V nodeValue = node.getValue();
1 ✔
2348
      if ((node.getKey() == null) || (nodeValue == null)
1 ✔
2349
          || (expired && !isComputingAsync(nodeValue))) {
1 ✔
2350
        scheduleDrainBuffers();
1 ✔
2351
      } else if (node.isAlive() && node.containsValue(value)) {
1 ✔
2352
        return true;
1 ✔
2353
      }
2354
    }
1 ✔
2355
    return false;
1 ✔
2356
  }
2357

2358
  @Override
2359
  public @Nullable V get(@Nullable Object key) {
2360
    requireNonNull(key);
1 ✔
2361
    return getIfPresent(key, /* recordStats= */ false);
1 ✔
2362
  }
2363

2364
  @Override
2365
  public @Nullable V getIfPresent(Object key, boolean recordStats) {
2366
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
2367
    if (node == null) {
1 ✔
2368
      if (recordStats) {
1 ✔
2369
        statsCounter().recordMisses(1);
1 ✔
2370
      }
2371
      if (drainStatusOpaque() == REQUIRED) {
1 ✔
2372
        scheduleDrainBuffers();
1 ✔
2373
      }
2374
      return null;
1 ✔
2375
    }
2376

2377
    long now = expirationTicker().read();
1 ✔
2378
    boolean expired = hasExpired(node, now);
1 ✔
2379
    V value = node.getValue();
1 ✔
2380
    if ((value == null) || (expired && !isComputingAsync(value))) {
1 ✔
2381
      if (recordStats) {
1 ✔
2382
        statsCounter().recordMisses(1);
1 ✔
2383
      }
2384
      scheduleDrainBuffers();
1 ✔
2385
      return null;
1 ✔
2386
    }
2387

2388
    if (expiresAfterRead() && !isComputingAsync(value)) {
1 ✔
2389
      @SuppressWarnings("unchecked")
2390
      var castedKey = (K) key;
1 ✔
2391
      setAccessTime(node, now);
1 ✔
2392
      tryExpireAfterRead(node, castedKey, value, expiry(), now);
1 ✔
2393
    }
2394
    V refreshed = afterRead(node, now, recordStats);
1 ✔
2395
    return (refreshed == null) ? value : refreshed;
1 ✔
2396
  }
2397

2398
  @Override
2399
  public @Nullable V getIfPresentQuietly(Object key) {
2400
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
2401
    if (node == null) {
1 ✔
2402
      return null;
1 ✔
2403
    }
2404
    boolean expired = hasExpired(node, expirationTicker().read());
1 ✔
2405
    V value = node.getValue();
1 ✔
2406
    if ((value == null) || (expired && !isComputingAsync(value))) {
1 ✔
2407
      return null;
1 ✔
2408
    }
2409
    return value;
1 ✔
2410
  }
2411

2412
  /**
2413
   * Returns the key associated with the mapping in this cache, or {@code null} if there is none.
2414
   *
2415
   * @param key the key whose canonical instance is to be returned
2416
   * @return the key used by the mapping, or {@code null} if this cache does not contain a mapping
2417
   *         for the key
2418
   * @throws NullPointerException if the specified key is null
2419
   */
2420
  public @Nullable K getKey(K key) {
2421
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
2422
    if (node == null) {
1 ✔
2423
      if (drainStatusOpaque() == REQUIRED) {
1 ✔
2424
        scheduleDrainBuffers();
1 ✔
2425
      }
2426
      return null;
1 ✔
2427
    }
2428
    afterRead(node, /* now= */ 0L, /* recordHit= */ false);
1 ✔
2429
    return node.getKey();
1 ✔
2430
  }
2431

2432
  @Override
2433
  public int getAllPresent(Map<K, @Nullable V> result, boolean retainAbsent) {
2434
    @Var int absent = 0;
1 ✔
2435
    @Var boolean drain = false;
1 ✔
2436
    int uniqueKeys = result.size();
1 ✔
2437
    long now = expirationTicker().read();
1 ✔
2438
    for (var iter = result.entrySet().iterator(); iter.hasNext();) {
1 ✔
2439
      var entry = iter.next();
1 ✔
2440
      Node<K, V> node = data.get(nodeFactory.newLookupKey(entry.getKey()));
1 ✔
2441
      if (node != null) {
1 ✔
2442
        boolean expired = hasExpired(node, now);
1 ✔
2443
        V value = node.getValue();
1 ✔
2444
        if ((value != null) && !expired) {
1 ✔
2445
          setAccessTime(node, now);
1 ✔
2446
          tryExpireAfterRead(node, entry.getKey(), value, expiry(), now);
1 ✔
2447
          V refreshed = afterRead(node, now, /* recordHit= */ false);
1 ✔
2448
          entry.setValue((refreshed == null) ? value : refreshed);
1 ✔
2449
          continue;
1 ✔
2450
        }
2451
        drain = true;
1 ✔
2452
      }
2453
      absent++;
1 ✔
2454
      if (!retainAbsent) {
1 ✔
2455
        iter.remove();
1 ✔
2456
      }
2457
    }
1 ✔
2458
    if (drain) {
1 ✔
2459
      scheduleDrainBuffers();
1 ✔
2460
    }
2461
    statsCounter().recordHits(uniqueKeys - absent);
1 ✔
2462
    statsCounter().recordMisses(absent);
1 ✔
2463
    return absent;
1 ✔
2464
  }
2465

2466
  @Override
2467
  public void putAll(Map<? extends K, ? extends V> map) {
2468
    map.forEach(this::put);
1 ✔
2469
  }
1 ✔
2470

2471
  @Override
2472
  public @Nullable V put(K key, V value) {
2473
    return put(key, value, expiry(), /* onlyIfAbsent= */ false);
1 ✔
2474
  }
2475

2476
  @Override
2477
  public @Nullable V putIfAbsent(K key, V value) {
2478
    return put(key, value, expiry(), /* onlyIfAbsent= */ true);
1 ✔
2479
  }
2480

2481
  /**
2482
   * Adds a node to the policy and the data store. If an existing node is found, then its value is
2483
   * updated if allowed.
2484
   *
2485
   * @param key key with which the specified value is to be associated
2486
   * @param value value to be associated with the specified key
2487
   * @param expiry the calculator for the write expiration time
2488
   * @param onlyIfAbsent a write is performed only if the key is not already associated with a value
2489
   * @return the prior value in or null if no mapping was found
2490
   */
2491
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2492
  @Nullable V put(K key, V value, Expiry<K, V> expiry, boolean onlyIfAbsent) {
2493
    requireNonNull(key);
1 ✔
2494
    requireNonNull(value);
1 ✔
2495

2496
    @Var int newWeight = -1;
1 ✔
2497
    @Var Object keyRef = null;
1 ✔
2498
    @Var Node<K, V> node = null;
1 ✔
2499
    Object lookupKey = nodeFactory.newLookupKey(key);
1 ✔
2500
    for (int attempts = 1; ; attempts++) {
1 ✔
2501
      @Var Node<K, V> prior = data.get(lookupKey);
1 ✔
2502
      if (prior == null) {
1 ✔
2503
        if (node == null) {
1 ✔
2504
          if (newWeight < 0) {
1 ✔
2505
            newWeight = weigher.weigh(key, value);
1 ✔
2506
          }
2507
          long now = expirationTicker().read();
1 ✔
2508
          keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1 ✔
2509
          node = nodeFactory.newNode(keyRef, value, valueReferenceQueue(), newWeight, now);
1 ✔
2510
          long expirationTime = expirationTimeFor(value, now);
1 ✔
2511
          setVariableTime(node, expireAfterCreate(key, value, expiry, now));
1 ✔
2512
          setAccessTime(node, expirationTime);
1 ✔
2513
          setWriteTime(node, expirationTime);
1 ✔
2514
        }
2515
        var newNode = node;
1 ✔
2516
        var newKeyRef = requireNonNull(keyRef);
1 ✔
2517
        prior = (cacheLoader == null)
1 ✔
2518
            ? data.putIfAbsent(newKeyRef, newNode)
1 ✔
2519
            : data.computeIfAbsent(newKeyRef, k -> {
1 ✔
2520
                discardRefresh(k);
1 ✔
2521
                return newNode;
1 ✔
2522
              });
2523
        if ((prior == null) || (prior == node)) {
1 ✔
2524
          afterWrite(new AddTask(node, newWeight));
1 ✔
2525
          return null;
1 ✔
2526
        }
2527
      }
2528
      if (onlyIfAbsent) {
1 ✔
2529
        // An optimistic fast path to avoid unnecessary locking
2530
        long now = expirationTicker().read();
1 ✔
2531
        boolean expired = hasExpired(prior, now);
1 ✔
2532
        V currentValue = prior.getValue();
1 ✔
2533
        if ((currentValue != null) && (!expired || isComputingAsync(currentValue))) {
1 ✔
2534
          if (!isComputingAsync(currentValue)) {
1 ✔
2535
            tryExpireAfterRead(prior, key, currentValue, expiry, now);
1 ✔
2536
            setAccessTime(prior, now);
1 ✔
2537
          }
2538
          afterRead(prior, now, /* recordHit= */ false);
1 ✔
2539
          return currentValue;
1 ✔
2540
        }
2541
      }
2542

2543
      // A read may race with the entry's removal, so that after the entry is acquired it may no
2544
      // longer be usable. A retry will reread from the map and either find an absent mapping, a
2545
      // new entry, or a stale entry.
2546
      if (!prior.isAlive()) {
1 ✔
2547
        // A reread of the stale entry may occur if the state transition occurred but the map
2548
        // removal was delayed by a context switch, so that this thread spin waits until resolved.
2549
        if ((attempts & MAX_PUT_SPIN_WAIT_ATTEMPTS) != 0) {
1 ✔
2550
          Thread.onSpinWait();
1 ✔
2551
          continue;
1 ✔
2552
        }
2553

2554
        // If the spin wait attempts are exhausted then fallback to a map computation in order to
2555
        // deschedule this thread until the entry's removal completes. If the key was modified
2556
        // while in the map so that its equals or hashCode changed then the contents may be
2557
        // corrupted, where the cache holds an evicted (dead) entry that could not be removed.
2558
        // That is a violation of the Map contract, so we check that the mapping is in the "alive"
2559
        // state while in the computation.
2560
        data.computeIfPresent(lookupKey, (k, n) -> {
1 ✔
2561
          requireIsAlive(key, n);
1 ✔
2562
          return n;
1 ✔
2563
        });
2564
        continue;
1 ✔
2565
      }
2566

2567
      long now;
2568
      V oldValue;
2569
      long varTime;
2570
      int oldWeight;
2571
      @Var boolean expired = false;
1 ✔
2572
      @Var boolean mayUpdate = true;
1 ✔
2573
      @Var boolean exceedsTolerance = false;
1 ✔
2574
      if (newWeight < 0) {
1 ✔
2575
        newWeight = weigher.weigh(key, value);
1 ✔
2576
      }
2577
      synchronized (prior) {
1 ✔
2578
        if (!prior.isAlive()) {
1 ✔
2579
          continue;
1 ✔
2580
        }
2581
        oldValue = prior.getValue();
1 ✔
2582
        oldWeight = prior.getWeight();
1 ✔
2583
        now = expirationTicker().read();
1 ✔
2584
        if (oldValue == null) {
1 ✔
2585
          varTime = expireAfterCreate(key, value, expiry, now);
1 ✔
2586
          notifyEviction(key, null, RemovalCause.COLLECTED);
1 ✔
2587
        } else if (hasExpired(prior, now) && !isComputingAsync(oldValue)) {
1 ✔
2588
          expired = true;
1 ✔
2589
          varTime = expireAfterCreate(key, value, expiry, now);
1 ✔
2590
          notifyEviction(key, oldValue, RemovalCause.EXPIRED);
1 ✔
2591
        } else if (onlyIfAbsent) {
1 ✔
2592
          mayUpdate = false;
1 ✔
2593
          varTime = expireAfterRead(prior, key, oldValue, expiry, now);
1 ✔
2594
        } else {
2595
          varTime = expireAfterUpdate(prior, key, value, expiry, now);
1 ✔
2596
        }
2597

2598
        long expirationTime = expirationTimeFor(mayUpdate ? value : oldValue, now);
1 ✔
2599
        if (mayUpdate) {
1 ✔
2600
          exceedsTolerance = exceedsWriteTimeTolerance(prior, varTime, expirationTime);
1 ✔
2601
          prior.setValue(value, valueReferenceQueue());
1 ✔
2602
          prior.setWeight(newWeight);
1 ✔
2603
          if (expired || (oldValue == null) || exceedsTolerance) {
1 ✔
2604
            setWriteTime(prior, expirationTime);
1 ✔
2605
          }
2606

2607
          discardRefresh(lookupKey);
1 ✔
2608
        }
2609

2610
        setVariableTime(prior, varTime);
1 ✔
2611
        setAccessTime(prior, expirationTime);
1 ✔
2612
      }
1 ✔
2613

2614
      if (expired) {
1 ✔
2615
        statsCounter().recordEviction(oldWeight, RemovalCause.EXPIRED);
1 ✔
2616
        notifyRemoval(key, oldValue, RemovalCause.EXPIRED);
1 ✔
2617
      } else if (oldValue == null) {
1 ✔
2618
        statsCounter().recordEviction(oldWeight, RemovalCause.COLLECTED);
1 ✔
2619
        notifyRemoval(key, /* value= */ null, RemovalCause.COLLECTED);
1 ✔
2620
      } else if (mayUpdate) {
1 ✔
2621
        notifyOnReplace(key, oldValue, value);
1 ✔
2622
      }
2623

2624
      int weightedDifference = mayUpdate ? (newWeight - oldWeight) : 0;
1 ✔
2625
      if ((oldValue == null) || (weightedDifference != 0) || expired) {
1 ✔
2626
        var access = (expired || (oldValue == null)) ? Access.RELOAD : Access.HIT;
1 ✔
2627
        afterWrite(new UpdateTask(prior, weightedDifference, access));
1 ✔
2628
      } else if (!onlyIfAbsent && exceedsTolerance) {
1 ✔
2629
        afterWrite(new UpdateTask(prior, weightedDifference));
1 ✔
2630
      } else {
2631
        afterRead(prior, now, /* recordHit= */ false);
1 ✔
2632
      }
2633

2634
      return expired ? null : oldValue;
1 ✔
2635
    }
2636
  }
2637

2638
  @Override
2639
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2640
  public @Nullable V remove(@Nullable Object key) {
2641
    requireNonNull(key);
1 ✔
2642

2643
    var ctx = new RemoveContext<K, V>();
1 ✔
2644
    Object lookupKey = nodeFactory.newLookupKey(key);
1 ✔
2645
    data.compute(lookupKey, (k, n) -> {
1 ✔
2646
      if (n == null) {
1 ✔
2647
        discardRefresh(k);
1 ✔
2648
        return null;
1 ✔
2649
      }
2650
      synchronized (n) {
1 ✔
2651
        requireIsAlive(key, n);
1 ✔
2652
        ctx.oldKey = n.getKey();
1 ✔
2653
        ctx.oldValue = n.getValue();
1 ✔
2654
        ctx.oldWeight = n.getWeight();
1 ✔
2655
        RemovalCause actualCause;
2656
        if ((ctx.oldKey == null) || (ctx.oldValue == null)) {
1 ✔
2657
          actualCause = RemovalCause.COLLECTED;
1 ✔
2658
        } else if (hasExpired(n, expirationTicker().read()) && !isComputingAsync(ctx.oldValue)) {
1 ✔
2659
          actualCause = RemovalCause.EXPIRED;
1 ✔
2660
        } else {
2661
          actualCause = RemovalCause.EXPLICIT;
1 ✔
2662
        }
2663
        if (actualCause.wasEvicted()) {
1 ✔
2664
          notifyEviction(ctx.oldKey, ctx.oldValue, actualCause);
1 ✔
2665
        }
2666
        ctx.cause = actualCause;
1 ✔
2667
        discardRefresh(k);
1 ✔
2668
        ctx.node = n;
1 ✔
2669
        n.retire();
1 ✔
2670
        return null;
1 ✔
2671
      }
2672
    });
2673

2674
    if (ctx.cause != null) {
1 ✔
2675
      afterWrite(new RemovalTask(requireNonNull(ctx.node)));
1 ✔
2676
      if (ctx.cause.wasEvicted()) {
1 ✔
2677
        statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1 ✔
2678
      }
2679
      notifyRemoval(ctx.oldKey, ctx.oldValue, ctx.cause);
1 ✔
2680
    }
2681
    return (ctx.cause == RemovalCause.EXPLICIT) ? ctx.oldValue : null;
1 ✔
2682
  }
2683

2684
  @Override
2685
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2686
  public boolean remove(@Nullable Object key, @Nullable Object value) {
2687
    requireNonNull(key);
1 ✔
2688
    if (value == null) {
1 ✔
2689
      return false;
1 ✔
2690
    }
2691

2692
    var ctx = new RemoveContext<K, V>();
1 ✔
2693
    Object lookupKey = nodeFactory.newLookupKey(key);
1 ✔
2694
    data.computeIfPresent(lookupKey, (kR, node) -> {
1 ✔
2695
      synchronized (node) {
1 ✔
2696
        requireIsAlive(key, node);
1 ✔
2697
        ctx.oldKey = node.getKey();
1 ✔
2698
        ctx.oldValue = node.getValue();
1 ✔
2699
        ctx.oldWeight = node.getWeight();
1 ✔
2700
        if ((ctx.oldKey == null) || (ctx.oldValue == null)) {
1 ✔
2701
          ctx.cause = RemovalCause.COLLECTED;
1 ✔
2702
        } else if (hasExpired(node, expirationTicker().read()) && !isComputingAsync(ctx.oldValue)) {
1 ✔
2703
          ctx.cause = RemovalCause.EXPIRED;
1 ✔
2704
        } else if (node.containsValue(value)) {
1 ✔
2705
          ctx.cause = RemovalCause.EXPLICIT;
1 ✔
2706
        } else {
2707
          return node;
1 ✔
2708
        }
2709
        if (ctx.cause.wasEvicted()) {
1 ✔
2710
          notifyEviction(ctx.oldKey, ctx.oldValue, ctx.cause);
1 ✔
2711
        }
2712
        discardRefresh(kR);
1 ✔
2713
        ctx.node = node;
1 ✔
2714
        node.retire();
1 ✔
2715
        return null;
1 ✔
2716
      }
2717
    });
2718

2719
    if (ctx.node == null) {
1 ✔
2720
      return false;
1 ✔
2721
    }
2722
    var removeCause = requireNonNull(ctx.cause);
1 ✔
2723
    afterWrite(new RemovalTask(ctx.node));
1 ✔
2724
    if (removeCause.wasEvicted()) {
1 ✔
2725
      statsCounter().recordEviction(ctx.oldWeight, removeCause);
1 ✔
2726
    }
2727
    notifyRemoval(ctx.oldKey, ctx.oldValue, removeCause);
1 ✔
2728

2729
    return (removeCause == RemovalCause.EXPLICIT);
1 ✔
2730
  }
2731

2732
  @Override
2733
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2734
  public @Nullable V replace(K key, V value) {
2735
    requireNonNull(key);
1 ✔
2736
    requireNonNull(value);
1 ✔
2737
    var ctx = new ReplaceContext<K, V>();
1 ✔
2738
    int weight = weigher.weigh(key, value);
1 ✔
2739
    Node<K, V> node = data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> {
1 ✔
2740
      synchronized (n) {
1 ✔
2741
        requireIsAlive(key, n);
1 ✔
2742
        ctx.nodeKey = n.getKey();
1 ✔
2743
        ctx.oldValue = n.getValue();
1 ✔
2744
        ctx.oldWeight = n.getWeight();
1 ✔
2745
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)
1 ✔
2746
            || (hasExpired(n, ctx.now = expirationTicker().read())
1 ✔
2747
                && !isComputingAsync(ctx.oldValue))) {
1 ✔
2748
          ctx.oldValue = null;
1 ✔
2749
          ctx.garbage = true;
1 ✔
2750
          return n;
1 ✔
2751
        }
2752

2753
        long varTime = expireAfterUpdate(n, key, value, expiry(), ctx.now);
1 ✔
2754
        n.setValue(value, valueReferenceQueue());
1 ✔
2755
        n.setWeight(weight);
1 ✔
2756

2757
        long expirationTime = expirationTimeFor(value, ctx.now);
1 ✔
2758
        ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1 ✔
2759
        if (ctx.exceedsTolerance) {
1 ✔
2760
          setWriteTime(n, expirationTime);
1 ✔
2761
        }
2762
        setAccessTime(n, expirationTime);
1 ✔
2763
        setVariableTime(n, varTime);
1 ✔
2764
        discardRefresh(k);
1 ✔
2765
        return n;
1 ✔
2766
      }
2767
    });
2768

2769
    if ((node == null) || (ctx.nodeKey == null) || (ctx.oldValue == null)) {
1 ✔
2770
      if (ctx.garbage) {
1 ✔
2771
        scheduleDrainBuffers();
1 ✔
2772
      }
2773
      return null;
1 ✔
2774
    }
2775

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

2783
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, value);
1 ✔
2784
    return ctx.oldValue;
1 ✔
2785
  }
2786

2787
  @Override
2788
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2789
  public boolean replace(K key, V oldValue, V newValue,
2790
      boolean shouldDiscardRefresh, boolean quietly) {
2791
    requireNonNull(key);
1 ✔
2792
    requireNonNull(oldValue);
1 ✔
2793
    requireNonNull(newValue);
1 ✔
2794
    var ctx = new ReplaceContext<K, V>();
1 ✔
2795
    int weight = weigher.weigh(key, newValue);
1 ✔
2796
    Node<K, V> node = data.computeIfPresent(nodeFactory.newLookupKey(key), (k, n) -> {
1 ✔
2797
      synchronized (n) {
1 ✔
2798
        requireIsAlive(key, n);
1 ✔
2799
        ctx.nodeKey = n.getKey();
1 ✔
2800
        ctx.oldValue = n.getValue();
1 ✔
2801
        ctx.oldWeight = n.getWeight();
1 ✔
2802
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)
1 ✔
2803
            || (hasExpired(n, ctx.now = expirationTicker().read())
1 ✔
2804
                && !isComputingAsync(ctx.oldValue))) {
1 ✔
2805
          ctx.oldValue = null;
1 ✔
2806
          ctx.garbage = true;
1 ✔
2807
          return n;
1 ✔
2808
        } else if (!n.containsValue(oldValue)) {
1 ✔
2809
          ctx.oldValue = null;
1 ✔
2810
          return n;
1 ✔
2811
        }
2812

2813
        // A completion finalizes only what the insertion deferred. Its caller reads the future's
2814
        // readiness before the write, so a value that becomes available in between is evaluated by
2815
        // the insertion, and evaluating it again would charge that creation as an update.
2816
        long varTime = (quietly && !isExpirationDeferred(n, ctx.now))
1 ✔
2817
            ? n.getVariableTime()
1 ✔
2818
            : expireAfterUpdate(n, key, newValue, expiry(), ctx.now);
1 ✔
2819
        n.setValue(newValue, valueReferenceQueue());
1 ✔
2820
        n.setWeight(weight);
1 ✔
2821

2822
        long expirationTime = expirationTimeFor(newValue, ctx.now);
1 ✔
2823
        ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1 ✔
2824
        if (ctx.exceedsTolerance) {
1 ✔
2825
          setWriteTime(n, expirationTime);
1 ✔
2826
        }
2827
        setAccessTime(n, expirationTime);
1 ✔
2828
        setVariableTime(n, varTime);
1 ✔
2829

2830
        if (shouldDiscardRefresh) {
1 ✔
2831
          discardRefresh(k);
1 ✔
2832
        }
2833
      }
1 ✔
2834
      return n;
1 ✔
2835
    });
2836

2837
    if ((node == null) || (ctx.nodeKey == null) || (ctx.oldValue == null)) {
1 ✔
2838
      if (ctx.garbage) {
1 ✔
2839
        scheduleDrainBuffers();
1 ✔
2840
      }
2841
      return false;
1 ✔
2842
    }
2843

2844
    int weightedDifference = (weight - ctx.oldWeight);
1 ✔
2845
    if (ctx.exceedsTolerance || (weightedDifference != 0)) {
1 ✔
2846
      afterWrite(new UpdateTask(node, weightedDifference, quietly ? Access.QUIET : Access.HIT));
1 ✔
2847
    } else if (!quietly) {
1 ✔
2848
      afterRead(node, ctx.now, /* recordHit= */ false);
1 ✔
2849
    }
2850

2851
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, newValue);
1 ✔
2852
    return true;
1 ✔
2853
  }
2854

2855
  @Override
2856
  public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
2857
    requireNonNull(function);
1 ✔
2858

2859
    BiFunction<K, @Nullable V, V> remappingFunction = (key, oldValue) ->
1 ✔
2860
        requireNonNull(function.apply(key, requireNonNull(oldValue)));
1 ✔
2861
    for (K key : keySet()) {
1 ✔
2862
      Object lookupKey = nodeFactory.newLookupKey(key);
1 ✔
2863
      remap(key, lookupKey, remappingFunction, expiry(),
1 ✔
2864
          new ComputeContext<>(), /* computeIfAbsent= */ false);
2865
    }
1 ✔
2866
  }
1 ✔
2867

2868
  @Override
2869
  public @Nullable V computeIfAbsent(K key,
2870
      @Var Function<? super K, ? extends @Nullable V> mappingFunction,
2871
      boolean recordStats, boolean recordLoad) {
2872
    requireNonNull(key);
1 ✔
2873
    requireNonNull(mappingFunction);
1 ✔
2874

2875
    // An optimistic fast path to avoid unnecessary locking
2876
    Node<K, V> node = data.get(nodeFactory.newLookupKey(key));
1 ✔
2877
    if (node != null) {
1 ✔
2878
      long now = expirationTicker().read();
1 ✔
2879
      boolean expired = hasExpired(node, now);
1 ✔
2880
      V value = node.getValue();
1 ✔
2881
      if ((value != null) && (!expired || isComputingAsync(value))) {
1 ✔
2882
        if (expiresAfterRead() && !isComputingAsync(value)) {
1 ✔
2883
          tryExpireAfterRead(node, key, value, expiry(), now);
1 ✔
2884
          setAccessTime(node, now);
1 ✔
2885
        }
2886
        var refreshed = afterRead(node, now, /* recordHit= */ recordStats);
1 ✔
2887
        return (refreshed == null) ? value : refreshed;
1 ✔
2888
      }
2889
    }
2890
    if (recordStats) {
1 ✔
2891
      mappingFunction = statsAware(mappingFunction, recordLoad);
1 ✔
2892
    }
2893
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1 ✔
2894
    return doComputeIfAbsent(key, keyRef, mappingFunction, new ComputeContext<>(), recordStats);
1 ✔
2895
  }
2896

2897
  /** Returns the current value from a computeIfAbsent invocation. */
2898
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2899
  @Nullable V doComputeIfAbsent(K key, Object keyRef,
2900
      Function<? super K, ? extends @Nullable V> mappingFunction,
2901
      ComputeContext<K, V> ctx, boolean recordStats) {
2902
    Node<K, V> node = data.compute(keyRef, (k, n) -> {
1 ✔
2903
      if (n == null) {
1 ✔
2904
        ctx.newValue = mappingFunction.apply(key);
1 ✔
2905
        if (ctx.newValue == null) {
1 ✔
2906
          discardRefresh(k);
1 ✔
2907
          return null;
1 ✔
2908
        }
2909
        ctx.now = expirationTicker().read();
1 ✔
2910
        ctx.newWeight = weigher.weigh(key, ctx.newValue);
1 ✔
2911
        var created = nodeFactory.newNode(k, ctx.newValue,
1 ✔
2912
            valueReferenceQueue(), ctx.newWeight, ctx.now);
1 ✔
2913
        long expirationTime = expirationTimeFor(ctx.newValue, ctx.now);
1 ✔
2914
        setVariableTime(created, expireAfterCreate(key, ctx.newValue, expiry(), ctx.now));
1 ✔
2915
        setAccessTime(created, expirationTime);
1 ✔
2916
        setWriteTime(created, expirationTime);
1 ✔
2917
        discardRefresh(k);
1 ✔
2918
        return created;
1 ✔
2919
      }
2920

2921
      synchronized (n) {
1 ✔
2922
        requireIsAlive(key, n);
1 ✔
2923
        ctx.nodeKey = n.getKey();
1 ✔
2924
        ctx.oldValue = n.getValue();
1 ✔
2925
        ctx.oldWeight = n.getWeight();
1 ✔
2926
        RemovalCause actualCause;
2927
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)) {
1 ✔
2928
          actualCause = RemovalCause.COLLECTED;
1 ✔
2929
        } else if (hasExpired(n, ctx.now = expirationTicker().read())
1 ✔
2930
            && !isComputingAsync(ctx.oldValue)) {
1 ✔
2931
          actualCause = RemovalCause.EXPIRED;
1 ✔
2932
        } else {
2933
          return n;
1 ✔
2934
        }
2935

2936
        ctx.cause = actualCause;
1 ✔
2937
        notifyEviction(ctx.nodeKey, ctx.oldValue, actualCause);
1 ✔
2938

2939
        try {
2940
          ctx.newValue = mappingFunction.apply(key);
1 ✔
2941
          if (ctx.newValue == null) {
1 ✔
2942
            discardRefresh(k);
1 ✔
2943
            ctx.removed = n;
1 ✔
2944
            n.retire();
1 ✔
2945
            return null;
1 ✔
2946
          }
2947
          ctx.now = expirationTicker().read();
1 ✔
2948
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1 ✔
2949
          long varTime = expireAfterCreate(key, ctx.newValue, expiry(), ctx.now);
1 ✔
2950

2951
          n.setValue(ctx.newValue, valueReferenceQueue());
1 ✔
2952
          n.setWeight(ctx.newWeight);
1 ✔
2953

2954
          long expirationTime = expirationTimeFor(ctx.newValue, ctx.now);
1 ✔
2955
          setAccessTime(n, expirationTime);
1 ✔
2956
          setWriteTime(n, expirationTime);
1 ✔
2957
          setVariableTime(n, varTime);
1 ✔
2958
          discardRefresh(k);
1 ✔
2959
          return n;
1 ✔
2960
        } catch (Throwable e) {
1 ✔
2961
          ctx.newValue = null;
1 ✔
2962
          discardRefresh(k);
1 ✔
2963
          ctx.exception = e;
1 ✔
2964
          ctx.removed = n;
1 ✔
2965
          n.retire();
1 ✔
2966
          return null;
1 ✔
2967
        }
2968
      }
2969
    });
2970

2971
    if (ctx.cause != null) {
1 ✔
2972
      statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1 ✔
2973
      notifyRemoval(ctx.nodeKey, ctx.oldValue, ctx.cause);
1 ✔
2974
    }
2975
    if (node == null) {
1 ✔
2976
      if (ctx.removed != null) {
1 ✔
2977
        afterWrite(new RemovalTask(ctx.removed));
1 ✔
2978
      }
2979
      if (ctx.exception != null) {
1 ✔
2980
        throw toUnchecked(ctx.exception);
1 ✔
2981
      }
2982
      return null;
1 ✔
2983
    }
2984
    if ((ctx.oldValue != null) && (ctx.newValue == null)) {
1 ✔
2985
      if (!isComputingAsync(ctx.oldValue)) {
1 ✔
2986
        tryExpireAfterRead(node, key, ctx.oldValue, expiry(), ctx.now);
1 ✔
2987
        setAccessTime(node, ctx.now);
1 ✔
2988
      }
2989

2990
      var refreshed = afterRead(node, ctx.now, /* recordHit= */ recordStats);
1 ✔
2991
      return (refreshed == null) ? ctx.oldValue : refreshed;
1 ✔
2992
    }
2993
    if ((ctx.oldValue == null) && (ctx.cause == null)) {
1 ✔
2994
      afterWrite(new AddTask(node, ctx.newWeight));
1 ✔
2995
    } else {
2996
      int weightedDifference = (ctx.newWeight - ctx.oldWeight);
1 ✔
2997
      afterWrite(new UpdateTask(node, weightedDifference, Access.RELOAD));
1 ✔
2998
    }
2999

3000
    return ctx.newValue;
1 ✔
3001
  }
3002

3003
  @Override
3004
  public @Nullable V computeIfPresent(K key,
3005
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction) {
3006
    requireNonNull(key);
1 ✔
3007
    requireNonNull(remappingFunction);
1 ✔
3008

3009
    // An optimistic fast path to avoid unnecessary locking
3010
    Object lookupKey = nodeFactory.newLookupKey(key);
1 ✔
3011
    var node = data.get(lookupKey);
1 ✔
3012
    if (node == null) {
1 ✔
3013
      return null;
1 ✔
3014
    }
3015
    boolean expired = hasExpired(node, expirationTicker().read());
1 ✔
3016
    V value = node.getValue();
1 ✔
3017
    if ((value == null) || expired) {
1 ✔
3018
      scheduleDrainBuffers();
1 ✔
3019
      return null;
1 ✔
3020
    }
3021

3022
    @SuppressWarnings("NullAway")
3023
    BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> statsAwareRemappingFunction =
1 ✔
3024
        statsAware(remappingFunction, /* recordLoad= */ true);
1 ✔
3025
    return remap(key, lookupKey, statsAwareRemappingFunction,
1 ✔
3026
        expiry(), new ComputeContext<>(), /* computeIfAbsent= */ false);
1 ✔
3027
  }
3028

3029
  @Override
3030
  public @Nullable V compute(K key,
3031
      BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
3032
      @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad,
3033
      @Nullable RemapHints hints) {
3034
    requireNonNull(key);
1 ✔
3035
    requireNonNull(remappingFunction);
1 ✔
3036

3037
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1 ✔
3038
    var ctx = new ComputeContext<K, V>();
1 ✔
3039
    ctx.hints = hints;
1 ✔
3040
    return remap(key, keyRef, statsAware(remappingFunction, recordLoad),
1 ✔
3041
        expiry, ctx, /* computeIfAbsent= */ true);
3042
  }
3043

3044
  @Override
3045
  public @Nullable V merge(K key, V value,
3046
      BiFunction<? super V, ? super V, ? extends @Nullable V> remappingFunction) {
3047
    requireNonNull(key);
1 ✔
3048
    requireNonNull(value);
1 ✔
3049
    requireNonNull(remappingFunction);
1 ✔
3050

3051
    Object keyRef = nodeFactory.newReferenceKey(key, keyReferenceQueue());
1 ✔
3052
    BiFunction<? super V, ? super V, ? extends @Nullable V> f = statsAware(remappingFunction);
1 ✔
3053
    return remap(key, keyRef,
1 ✔
3054
        (k, oldValue) -> (oldValue == null) ? value : f.apply(oldValue, value), expiry(),
1 ✔
3055
        new ComputeContext<>(), /* computeIfAbsent= */ true);
3056
  }
3057

3058
  /**
3059
   * Attempts to compute a mapping for the specified key and its current mapped value (or
3060
   * {@code null} if there is no current mapping).
3061
   * <p>
3062
   * An entry that has expired or been reference collected is evicted and the computation continues
3063
   * as if the entry had not been present. This method does not pre-screen and does not wrap the
3064
   * remappingFunction to be statistics aware.
3065
   *
3066
   * @param key key with which the specified value is to be associated
3067
   * @param keyRef the key to associate with or a lookup only key if not {@code computeIfAbsent}
3068
   * @param remappingFunction the function to compute a value
3069
   * @param expiry the calculator for the expiration time
3070
   * @param ctx the mutable context for passing state to and from the compute lambda
3071
   * @param computeIfAbsent if an absent entry can be computed
3072
   * @return the new value associated with the specified key, or null if none
3073
   */
3074
  @SuppressWarnings({"StatementWithEmptyBody", "SynchronizationOnLocalVariableOrMethodParameter"})
3075
  @Nullable V remap(K key, Object keyRef,
3076
      BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
3077
      @Nullable Expiry<? super K, ? super V> expiry,
3078
      ComputeContext<K, V> ctx, boolean computeIfAbsent) {
3079
    Node<K, V> node = data.compute(keyRef, (kr, n) -> {
1 ✔
3080
      if (n == null) {
1 ✔
3081
        if (!computeIfAbsent) {
1 ✔
3082
          return null;
1 ✔
3083
        }
3084
        ctx.newValue = remappingFunction.apply(key, null);
1 ✔
3085
        if (ctx.newValue == null) {
1 ✔
3086
          // A stale refresh whose entry is absent leaves a successor's registration intact
3087
          if ((ctx.hints == null) || !ctx.hints.preserveRefresh) {
1 ✔
3088
            discardRefresh(kr);
1 ✔
3089
          }
3090
          return null;
1 ✔
3091
        }
3092
        try {
3093
          ctx.now = expirationTicker().read();
1 ✔
3094
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1 ✔
3095
          long varTime = expireAfterCreate(key, ctx.newValue, expiry, ctx.now);
1 ✔
3096
          var created = nodeFactory.newNode(keyRef, ctx.newValue,
1 ✔
3097
              valueReferenceQueue(), ctx.newWeight, ctx.now);
1 ✔
3098

3099
          long expirationTime = expirationTimeFor(ctx.newValue, ctx.now);
1 ✔
3100
          setAccessTime(created, expirationTime);
1 ✔
3101
          setWriteTime(created, expirationTime);
1 ✔
3102
          setVariableTime(created, varTime);
1 ✔
3103
          return created;
1 ✔
3104
        } finally {
3105
          discardRefresh(kr);
1 ✔
3106
        }
3107
      }
3108

3109
      synchronized (n) {
1 ✔
3110
        requireIsAlive(key, n);
1 ✔
3111
        ctx.nodeKey = n.getKey();
1 ✔
3112
        ctx.oldValue = n.getValue();
1 ✔
3113
        ctx.oldWeight = n.getWeight();
1 ✔
3114
        if ((ctx.nodeKey == null) || (ctx.oldValue == null)) {
1 ✔
3115
          ctx.cause = RemovalCause.COLLECTED;
1 ✔
3116
        } else if (hasExpired(n, expirationTicker().read()) && !isComputingAsync(ctx.oldValue)) {
1 ✔
3117
          ctx.cause = RemovalCause.EXPIRED;
1 ✔
3118
        }
3119
        if (ctx.cause != null) {
1 ✔
3120
          notifyEviction(ctx.nodeKey, ctx.oldValue, ctx.cause);
1 ✔
3121
          if (!computeIfAbsent) {
1 ✔
3122
            discardRefresh(kr);
1 ✔
3123
            ctx.removed = n;
1 ✔
3124
            n.retire();
1 ✔
3125
            return null;
1 ✔
3126
          }
3127
        }
3128

3129
        boolean wasEvicted = (ctx.cause != null);
1 ✔
3130
        try {
3131
          ctx.newValue = remappingFunction.apply(key,
1 ✔
3132
              (ctx.cause == null) ? ctx.oldValue : null);
1 ✔
3133

3134
          if (ctx.newValue == null) {
1 ✔
3135
            if (ctx.cause == null) {
1 ✔
3136
              ctx.cause = RemovalCause.EXPLICIT;
1 ✔
3137
            }
3138
            // A stale refresh whose entry was evicted leaves a successor's registration intact
3139
            if ((ctx.hints == null) || !ctx.hints.preserveRefresh) {
1 ✔
3140
              discardRefresh(kr);
1 ✔
3141
            }
3142
            ctx.removed = n;
1 ✔
3143
            n.retire();
1 ✔
3144
            return null;
1 ✔
3145
          }
3146

3147
          // If the caller flagged a same-instance return as a no-op (e.g., a refresh was rejected
3148
          // and should not touch the entry), skip the metadata updates below.
3149
          if ((ctx.hints != null) && ctx.hints.preserveTimestamps
1 ✔
3150
              && (ctx.newValue == ctx.oldValue) && (ctx.cause == null)) {
3151
            // Skip for query-style callers whose no-op path must leave any in-flight refresh intact
3152
            if (!ctx.hints.preserveRefresh) {
1 ✔
3153
              discardRefresh(kr);
1 ✔
3154
            }
3155
            ctx.unmodified = true;
1 ✔
3156
            return n;
1 ✔
3157
          }
3158

3159
          long varTime;
3160
          ctx.newWeight = weigher.weigh(key, ctx.newValue);
1 ✔
3161
          ctx.now = expirationTicker().read();
1 ✔
3162
          if (ctx.cause == null) {
1 ✔
3163
            if (ctx.newValue != ctx.oldValue) {
1 ✔
3164
              ctx.cause = RemovalCause.REPLACED;
1 ✔
3165
            }
3166
            varTime = expireAfterUpdate(n, key, ctx.newValue, expiry, ctx.now);
1 ✔
3167
          } else {
3168
            varTime = expireAfterCreate(key, ctx.newValue, expiry, ctx.now);
1 ✔
3169
          }
3170

3171
          if (ctx.newValue != ctx.oldValue) {
1 ✔
3172
            n.setValue(ctx.newValue, valueReferenceQueue());
1 ✔
3173
          }
3174
          n.setWeight(ctx.newWeight);
1 ✔
3175

3176
          long expirationTime = expirationTimeFor(ctx.newValue, ctx.now);
1 ✔
3177
          ctx.exceedsTolerance = exceedsWriteTimeTolerance(n, varTime, expirationTime);
1 ✔
3178
          if (((ctx.cause != null) && ctx.cause.wasEvicted()) || ctx.exceedsTolerance) {
1 ✔
3179
            setWriteTime(n, expirationTime);
1 ✔
3180
          }
3181
          setAccessTime(n, expirationTime);
1 ✔
3182
          setVariableTime(n, varTime);
1 ✔
3183
          discardRefresh(kr);
1 ✔
3184
          return n;
1 ✔
3185
        } catch (Throwable e) {
1 ✔
3186
          if ((ctx.hints == null) || !ctx.hints.preserveRefresh) {
1 ✔
3187
            discardRefresh(kr);
1 ✔
3188
          }
3189
          if (!wasEvicted) {
1 ✔
3190
            throw e;
1 ✔
3191
          }
3192
          ctx.newValue = null;
1 ✔
3193
          ctx.exception = e;
1 ✔
3194
          ctx.removed = n;
1 ✔
3195
          n.retire();
1 ✔
3196
          return null;
1 ✔
3197
        }
3198
      }
3199
    });
3200

3201
    if (ctx.cause != null) {
1 ✔
3202
      if (ctx.cause == RemovalCause.REPLACED) {
1 ✔
3203
        requireNonNull(ctx.newValue);
1 ✔
3204
        notifyOnReplace(key, ctx.oldValue, ctx.newValue);
1 ✔
3205
      } else {
3206
        if (ctx.cause.wasEvicted()) {
1 ✔
3207
          statsCounter().recordEviction(ctx.oldWeight, ctx.cause);
1 ✔
3208
        }
3209
        notifyRemoval(ctx.nodeKey, ctx.oldValue, ctx.cause);
1 ✔
3210
      }
3211
    }
3212

3213
    if (ctx.removed != null) {
1 ✔
3214
      afterWrite(new RemovalTask(ctx.removed));
1 ✔
3215
    } else if (node == null) {
1 ✔
3216
      // absent and not computable
3217
    } else if (ctx.unmodified) {
1 ✔
3218
      // caller flagged a same-instance return as a no-op
3219
    } else if ((ctx.oldValue == null) && (ctx.cause == null)) {
1 ✔
3220
      afterWrite(new AddTask(node, ctx.newWeight));
1 ✔
3221
    } else {
3222
      int weightedDifference = ctx.newWeight - ctx.oldWeight;
1 ✔
3223
      boolean quietly = (ctx.hints != null) && ctx.hints.quietly;
1 ✔
3224
      boolean reload = (ctx.cause != null) && ctx.cause.wasEvicted();
1 ✔
3225
      if (ctx.exceedsTolerance || (weightedDifference != 0) || (evicts() && !quietly && reload)) {
1 ✔
3226
        var access = quietly ? Access.QUIET : (reload ? Access.RELOAD : Access.HIT);
1 ✔
3227
        afterWrite(new UpdateTask(node, weightedDifference, access));
1 ✔
3228
      } else {
1 ✔
3229
        if (!quietly) {
1 ✔
3230
          afterRead(node, ctx.now, /* recordHit= */ false);
1 ✔
3231
        }
3232
        if (reload) {
1 ✔
3233
          scheduleDrainBuffers();
1 ✔
3234
        }
3235
      }
3236
    }
3237

3238
    if (ctx.exception != null) {
1 ✔
3239
      throw toUnchecked(ctx.exception);
1 ✔
3240
    }
3241
    return ctx.newValue;
1 ✔
3242
  }
3243

3244
  @Override
3245
  public void forEach(BiConsumer<? super K, ? super V> action) {
3246
    requireNonNull(action);
1 ✔
3247

3248
    for (var iterator = new EntryIterator<>(this); iterator.hasNext();) {
1 ✔
3249
      action.accept(requireNonNull(iterator.key), requireNonNull(iterator.value));
1 ✔
3250
      iterator.advance();
1 ✔
3251
    }
3252
  }
1 ✔
3253

3254
  @Override
3255
  public Set<K> keySet() {
3256
    Set<K> ks = keySet;
1 ✔
3257
    return (ks == null) ? (keySet = new KeySetView<>(this)) : ks;
1 ✔
3258
  }
3259

3260
  @Override
3261
  public Collection<V> values() {
3262
    Collection<V> vs = values;
1 ✔
3263
    return (vs == null) ? (values = new ValuesView<>(this)) : vs;
1 ✔
3264
  }
3265

3266
  @Override
3267
  public Set<Entry<K, V>> entrySet() {
3268
    Set<Entry<K, V>> es = entrySet;
1 ✔
3269
    return (es == null) ? (entrySet = new EntrySetView<>(this)) : es;
1 ✔
3270
  }
3271

3272
  /**
3273
   * Object equality requires reflexive, symmetric, transitive, and consistency properties. Of
3274
   * these, symmetry and consistency require further clarification for how they are upheld.
3275
   * <p>
3276
   * The <i>consistency</i> property between invocations requires that the results are the same if
3277
   * there are no modifications to the information used. Therefore, usages should expect that this
3278
   * operation may return misleading results if either the maps or the data held by them is modified
3279
   * during the execution of this method. This characteristic allows for comparing the map sizes and
3280
   * assuming stable mappings, as done by {@link java.util.AbstractMap}-based maps.
3281
   * <p>
3282
   * The <i>symmetric</i> property requires that the result is the same for all implementations of
3283
   * {@link Map#equals(Object)}. That contract is defined in terms of the stable mappings provided
3284
   * by {@link #entrySet()}, meaning that the {@link #size()} optimization forces that the count is
3285
   * consistent with the mappings when used for an equality check.
3286
   * <p>
3287
   * The cache's {@link #size()} method may include entries that have expired or have been reference
3288
   * collected, but have not yet been removed from the backing map. An iteration over the map may
3289
   * trigger the removal of these dead entries when skipped over during traversal. To ensure
3290
   * consistency and symmetry, usages should call {@link #cleanUp()} before this method while no
3291
   * other concurrent operations are being performed on this cache. This is not done implicitly by
3292
   * {@link #size()} as many usages assume it to be instantaneous and lock-free. As a postcondition
3293
   * the iteration count is verified against the prescreened {@link #size()} so that a concurrent
3294
   * maintenance pass that drops dead entries during traversal is detected and reported as not
3295
   * equal, rather than silently returning {@code true} on the surviving subset.
3296
   */
3297
  @Override
3298
  public boolean equals(@Nullable Object o) {
3299
    if (o == this) {
1 ✔
3300
      return true;
1 ✔
3301
    } else if (!(o instanceof Map)) {
1 ✔
3302
      return false;
1 ✔
3303
    }
3304

3305
    var map = (Map<?, ?>) o;
1 ✔
3306
    int expectedSize = size();
1 ✔
3307
    if (map.size() != expectedSize) {
1 ✔
3308
      return false;
1 ✔
3309
    }
3310

3311
    try {
3312
      @Var int count = 0;
1 ✔
3313
      long now = expirationTicker().read();
1 ✔
3314
      for (var node : data.values()) {
1 ✔
3315
        boolean expired = hasExpired(node, now);
1 ✔
3316
        K key = node.getKey();
1 ✔
3317
        V value = node.getValue();
1 ✔
3318
        if ((key == null) || (value == null) || !node.isAlive()
1 ✔
3319
            || (expired && !isComputingAsync(value))) {
1 ✔
3320
          scheduleDrainBuffers();
1 ✔
3321
          return false;
1 ✔
3322
        } else {
3323
          var val = map.get(key);
1 ✔
3324
          if ((val == null) || ((val != value) && !val.equals(value))) {
1 ✔
3325
            return false;
1 ✔
3326
          }
3327
        }
3328
        count++;
1 ✔
3329
      }
1 ✔
3330
      return (count == expectedSize);
1 ✔
3331
    } catch (ClassCastException | NullPointerException ignored) {
1 ✔
3332
      return false;
1 ✔
3333
    }
3334
  }
3335

3336
  @Override
3337
  public int hashCode() {
3338
    @Var int hash = 0;
1 ✔
3339
    @Var boolean drain = false;
1 ✔
3340
    long now = expirationTicker().read();
1 ✔
3341
    for (var node : data.values()) {
1 ✔
3342
      boolean expired = hasExpired(node, now);
1 ✔
3343
      K key = node.getKey();
1 ✔
3344
      V value = node.getValue();
1 ✔
3345
      if ((key == null) || (value == null) || !node.isAlive()
1 ✔
3346
          || (expired && !isComputingAsync(value))) {
1 ✔
3347
        drain = true;
1 ✔
3348
      } else {
3349
        hash += key.hashCode() ^ value.hashCode();
1 ✔
3350
      }
3351
    }
1 ✔
3352
    if (drain) {
1 ✔
3353
      scheduleDrainBuffers();
1 ✔
3354
    }
3355
    return hash;
1 ✔
3356
  }
3357

3358
  @Override
3359
  public String toString() {
3360
    @Var boolean drain = false;
1 ✔
3361
    long now = expirationTicker().read();
1 ✔
3362
    var result = new StringBuilder().append('{');
1 ✔
3363
    for (var node : data.values()) {
1 ✔
3364
      boolean expired = hasExpired(node, now);
1 ✔
3365
      K key = node.getKey();
1 ✔
3366
      V value = node.getValue();
1 ✔
3367
      if ((key == null) || (value == null) || !node.isAlive()
1 ✔
3368
          || (expired && !isComputingAsync(value))) {
1 ✔
3369
        drain = true;
1 ✔
3370
      } else {
3371
        if (result.length() != 1) {
1 ✔
3372
          result.append(',').append(' ');
1 ✔
3373
        }
3374
        result.append((key == this) ? "(this Map)" : key);
1 ✔
3375
        result.append('=');
1 ✔
3376
        result.append((value == this) ? "(this Map)" : value);
1 ✔
3377
      }
3378
    }
1 ✔
3379
    if (drain) {
1 ✔
3380
      scheduleDrainBuffers();
1 ✔
3381
    }
3382
    return result.append('}').toString();
1 ✔
3383
  }
3384

3385
  /**
3386
   * Returns the computed result from the ordered traversal of the cache entries.
3387
   *
3388
   * @param hottest the coldest or hottest iteration order
3389
   * @param transformer a function that unwraps the value
3390
   * @param mappingFunction the mapping function to compute a value
3391
   * @return the computed value
3392
   */
3393
  @SuppressWarnings("GuardedByChecker")
3394
  <T extends @Nullable Object> T evictionOrder(boolean hottest,
3395
      Function<@Nullable V, @Nullable V> transformer,
3396
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3397
    Comparator<Node<K, V>> comparator = Comparator.comparingInt(node -> {
1 ✔
3398
      var keyRef = node.getKeyReferenceOrNull();
1 ✔
3399
      return ((keyRef == null) || !node.isAlive()) ? 0 : frequencySketch().frequency(keyRef);
1 ✔
3400
    });
3401
    Iterable<Node<K, V>> iterable;
3402
    if (hottest) {
1 ✔
3403
      iterable = () -> {
1 ✔
3404
        var secondary = PeekingIterator.comparing(
1 ✔
3405
            accessOrderProbationDeque().descendingIterator(),
1 ✔
3406
            accessOrderWindowDeque().descendingIterator(), comparator);
1 ✔
3407
        return PeekingIterator.concat(
1 ✔
3408
            accessOrderProtectedDeque().descendingIterator(), secondary);
1 ✔
3409
      };
3410
    } else {
3411
      iterable = () -> {
1 ✔
3412
        var primary = PeekingIterator.comparing(
1 ✔
3413
            accessOrderWindowDeque().iterator(), accessOrderProbationDeque().iterator(),
1 ✔
3414
            comparator.reversed());
1 ✔
3415
        return PeekingIterator.concat(primary, accessOrderProtectedDeque().iterator());
1 ✔
3416
      };
3417
    }
3418
    return snapshot(iterable, transformer, mappingFunction);
1 ✔
3419
  }
3420

3421
  /**
3422
   * Returns the computed result from the ordered traversal of the cache entries.
3423
   *
3424
   * @param oldest the youngest or oldest iteration order
3425
   * @param transformer a function that unwraps the value
3426
   * @param mappingFunction the mapping function to compute a value
3427
   * @return the computed value
3428
   */
3429
  @SuppressWarnings("GuardedByChecker")
3430
  <T extends @Nullable Object> T expireAfterAccessOrder(boolean oldest,
3431
      Function<@Nullable V, @Nullable V> transformer,
3432
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3433
    Iterable<Node<K, V>> iterable;
3434
    if (evicts()) {
1 ✔
3435
      iterable = () -> {
1 ✔
3436
        @Var Comparator<Node<K, V>> comparator = (n1, n2) ->
1 ✔
3437
            Long.signum(n1.getAccessTime() - n2.getAccessTime());
1 ✔
3438
        PeekingIterator<Node<K, V>> first;
3439
        PeekingIterator<Node<K, V>> second;
3440
        PeekingIterator<Node<K, V>> third;
3441
        if (oldest) {
1 ✔
3442
          comparator = comparator.reversed();
1 ✔
3443
          first = accessOrderWindowDeque().iterator();
1 ✔
3444
          second = accessOrderProbationDeque().iterator();
1 ✔
3445
          third = accessOrderProtectedDeque().iterator();
1 ✔
3446
        } else {
3447
          first = accessOrderWindowDeque().descendingIterator();
1 ✔
3448
          second = accessOrderProbationDeque().descendingIterator();
1 ✔
3449
          third = accessOrderProtectedDeque().descendingIterator();
1 ✔
3450
        }
3451
        return PeekingIterator.comparing(
1 ✔
3452
            PeekingIterator.comparing(first, second, comparator), third, comparator);
1 ✔
3453
      };
3454
    } else {
3455
      iterable = oldest
1 ✔
3456
          ? accessOrderWindowDeque()
1 ✔
3457
          : accessOrderWindowDeque()::descendingIterator;
1 ✔
3458
    }
3459
    return snapshot(iterable, transformer, mappingFunction);
1 ✔
3460
  }
3461

3462
  /**
3463
   * Returns the computed result from the ordered traversal of the cache entries.
3464
   *
3465
   * @param iterable the supplier of the entries in the cache
3466
   * @param transformer a function that unwraps the value
3467
   * @param mappingFunction the mapping function to compute a value
3468
   * @return the computed value
3469
   */
3470
  @SuppressWarnings("MathClampLong")
3471
  <T extends @Nullable Object> T snapshot(Iterable<Node<K, V>> iterable,
3472
      Function<@Nullable V, @Nullable V> transformer,
3473
      Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
3474
    requireNonNull(mappingFunction);
1 ✔
3475
    requireNonNull(transformer);
1 ✔
3476
    requireNonNull(iterable);
1 ✔
3477

3478
    evictionLock.lock();
1 ✔
3479
    try {
3480
      maintenance(/* ignored */ null);
1 ✔
3481

3482
      // Obtain the iterator as late as possible for modification count checking
3483
      try (var stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(
1 ✔
3484
           iterable.iterator(), DISTINCT | ORDERED | NONNULL | IMMUTABLE), /* parallel= */ false)) {
1 ✔
3485
        boolean[] open = { true };
1 ✔
3486
        return mappingFunction.apply(stream.onClose(() -> open[0] = false)
1 ✔
3487
            .peek(ignored -> requireState(open[0], "stream has already been closed"))
1 ✔
3488
            .map(node -> nodeToCacheEntry(node, transformer,
1 ✔
3489
                (int) Math.max(0L, Math.min(node.getPolicyWeight(), Integer.MAX_VALUE))))
1 ✔
3490
            .filter(Objects::nonNull));
1 ✔
3491
      }
3492
    } finally {
3493
      evictionLock.unlock();
1 ✔
3494
      rescheduleCleanUpIfIncomplete();
1 ✔
3495
    }
3496
  }
3497

3498
  /**
3499
   * Returns an entry for the given node if it can be used externally, else null. The weight is
3500
   * the caller's best-effort reading and the timestamps are read after the value, so either may
3501
   * belong to a concurrent update.
3502
   */
3503
  @Nullable CacheEntry<K, V> nodeToCacheEntry(
3504
      Node<K, V> node, Function<@Nullable V, @Nullable V> transformer, int weight) {
3505
    long now = expirationTicker().read();
1 ✔
3506
    boolean expired = hasExpired(node, now);
1 ✔
3507
    V rawValue = node.getValue();
1 ✔
3508
    if (rawValue == null) {
1 ✔
3509
      return null;
1 ✔
3510
    }
3511
    V value = transformer.apply(rawValue);
1 ✔
3512
    K key = node.getKey();
1 ✔
3513
    if ((key == null) || (value == null) || !node.isAlive() || expired) {
1 ✔
3514
      return null;
1 ✔
3515
    }
3516

3517
    @Var long expiresAfter = Long.MAX_VALUE;
1 ✔
3518
    if (expiresAfterAccess()) {
1 ✔
3519
      expiresAfter = Math.min(expiresAfter,
1 ✔
3520
          expiresAfterAccessNanos() - Math.max(0L, now - node.getAccessTime()));
1 ✔
3521
    }
3522
    if (expiresAfterWrite()) {
1 ✔
3523
      expiresAfter = Math.min(expiresAfter,
1 ✔
3524
          expiresAfterWriteNanos() - Math.max(0L, toWriteTime(now) - writeTimeOf(node)));
1 ✔
3525
    }
3526
    if (expiresVariable()) {
1 ✔
3527
      expiresAfter = node.getVariableTime() - now;
1 ✔
3528
    }
3529

3530
    long refreshableAfter = refreshAfterWrite()
1 ✔
3531
        ? refreshAfterWriteNanos() - Math.max(0L, now - writeTimeOf(node))
1 ✔
3532
        : Long.MAX_VALUE;
1 ✔
3533
    return SnapshotEntry.forEntry(key, value, now,
1 ✔
3534
        isWeighted ? weight : 1, now + expiresAfter, now + refreshableAfter);
1 ✔
3535
  }
3536

3537
  /** Creates a serialization proxy based on the common configuration shared by all cache types. */
3538
  static <K, V> SerializationProxy<K, V> makeSerializationProxy(BoundedLocalCache<?, ?> cache) {
3539
    var proxy = new SerializationProxy<K, V>();
1 ✔
3540
    proxy.weakKeys = cache.collectKeys();
1 ✔
3541
    proxy.weakValues = cache.nodeFactory.weakValues();
1 ✔
3542
    proxy.softValues = cache.nodeFactory.softValues();
1 ✔
3543
    proxy.isRecordingStats = cache.isRecordingStats();
1 ✔
3544
    proxy.evictionListener = cache.evictionListener;
1 ✔
3545
    proxy.removalListener = cache.removalListener();
1 ✔
3546
    proxy.ticker = cache.expirationTicker();
1 ✔
3547
    if (cache.expiresAfterAccess()) {
1 ✔
3548
      proxy.expiresAfterAccessNanos = cache.expiresAfterAccessNanos();
1 ✔
3549
    }
3550
    if (cache.expiresAfterWrite()) {
1 ✔
3551
      proxy.expiresAfterWriteNanos = cache.expiresAfterWriteNanos();
1 ✔
3552
    }
3553
    if (cache.expiresVariable()) {
1 ✔
3554
      proxy.expiry = cache.expiry();
1 ✔
3555
    }
3556
    if (cache.refreshAfterWrite()) {
1 ✔
3557
      proxy.refreshAfterWriteNanos = cache.refreshAfterWriteNanos();
1 ✔
3558
    }
3559
    if (cache.evicts()) {
1 ✔
3560
      if (cache.isWeighted) {
1 ✔
3561
        proxy.weigher = cache.weigher;
1 ✔
3562
        proxy.maximumWeight = cache.maximumAcquire();
1 ✔
3563
      } else {
3564
        proxy.maximumSize = cache.maximumAcquire();
1 ✔
3565
      }
3566
    }
3567
    proxy.cacheLoader = cache.cacheLoader;
1 ✔
3568
    proxy.async = cache.isAsync;
1 ✔
3569
    return proxy;
1 ✔
3570
  }
3571

3572
  /** Mutable context for passing state between a lambda and the caller. */
3573
  static final class EvictContext<V> {
1 ✔
3574
    @Nullable RemovalCause cause;
3575
    @Nullable V value;
3576
    boolean resurrect;
3577
    boolean removed;
3578
    int oldWeight;
3579
  }
3580

3581
  /** Mutable context for passing state between a lambda and the caller. */
3582
  static final class RemoveContext<K, V> {
1 ✔
3583
    @Nullable K oldKey;
3584
    @Nullable V oldValue;
3585
    @Nullable Node<K, V> node;
3586
    @Nullable RemovalCause cause;
3587
    int oldWeight;
3588
  }
3589

3590
  /** Mutable context for passing state between a lambda and the caller. */
3591
  static final class ReplaceContext<K, V> {
1 ✔
3592
    @Nullable K nodeKey;
3593
    @Nullable V oldValue;
3594

3595
    long now;
3596
    int oldWeight;
3597
    boolean garbage;
3598
    boolean exceedsTolerance;
3599
  }
3600

3601
  /** Mutable context for passing state between a lambda and the caller. */
3602
  static final class ComputeContext<K, V> {
1 ✔
3603
    @Nullable K nodeKey;
3604
    @Nullable V oldValue;
3605
    @Nullable V newValue;
3606
    @Nullable RemapHints hints;
3607
    @Nullable Node<K, V> removed;
3608
    @Nullable RemovalCause cause;
3609
    @Nullable Throwable exception;
3610

3611
    long now;
3612
    int oldWeight;
3613
    int newWeight;
3614
    boolean unmodified;
3615
    boolean exceedsTolerance;
3616
  }
3617

3618
  /** A function that produces an unmodifiable map up to the limit in stream order. */
3619
  static final class SizeLimiter<K, V> implements Function<Stream<CacheEntry<K, V>>, Map<K, V>> {
3620
    private final int expectedSize;
3621
    private final long limit;
3622

3623
    SizeLimiter(int expectedSize, long limit) {
1 ✔
3624
      requireArgument(limit >= 0, "limit cannot be negative: %s", limit);
1 ✔
3625
      this.expectedSize = expectedSize;
1 ✔
3626
      this.limit = limit;
1 ✔
3627
    }
1 ✔
3628

3629
    @Override
3630
    public Map<K, V> apply(Stream<CacheEntry<K, V>> stream) {
3631
      var map = new LinkedHashMap<K, V>(calculateHashMapCapacity(expectedSize));
1 ✔
3632
      stream.limit(limit).forEach(entry -> map.put(entry.getKey(), entry.getValue()));
1 ✔
3633
      return Collections.unmodifiableMap(map);
1 ✔
3634
    }
3635
  }
3636

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

3641
    long weightedSize;
3642

3643
    WeightLimiter(long weightLimit) {
1 ✔
3644
      requireArgument(weightLimit >= 0, "weight limit cannot be negative: %s", weightLimit);
1 ✔
3645
      this.weightLimit = weightLimit;
1 ✔
3646
    }
1 ✔
3647

3648
    @Override
3649
    public Map<K, V> apply(Stream<CacheEntry<K, V>> stream) {
3650
      var map = new LinkedHashMap<K, V>();
1 ✔
3651
      stream.takeWhile(entry -> {
1 ✔
3652
        weightedSize += entry.weight();
1 ✔
3653
        if (weightedSize < 0) {
1 ✔
3654
          weightedSize = Long.MAX_VALUE;
1 ✔
3655
        }
3656
        return (weightedSize <= weightLimit);
1 ✔
3657
      }).forEach(entry -> map.put(entry.getKey(), entry.getValue()));
1 ✔
3658
      return Collections.unmodifiableMap(map);
1 ✔
3659
    }
3660
  }
3661

3662
  /** An adapter to safely externalize the keys. */
3663
  static final class KeySetView<K, V> extends AbstractSet<K> {
3664
    final BoundedLocalCache<K, V> cache;
3665

3666
    KeySetView(BoundedLocalCache<K, V> cache) {
1 ✔
3667
      this.cache = requireNonNull(cache);
1 ✔
3668
    }
1 ✔
3669

3670
    @Override
3671
    public int size() {
3672
      return cache.size();
1 ✔
3673
    }
3674

3675
    @Override
3676
    public void clear() {
3677
      cache.clear();
1 ✔
3678
    }
1 ✔
3679

3680
    @Override
3681
    @SuppressWarnings("SuspiciousMethodCalls")
3682
    public boolean contains(@Nullable Object o) {
3683
      return cache.containsKey(o);
1 ✔
3684
    }
3685

3686
    @Override
3687
    public boolean containsAll(Collection<?> collection) {
3688
      requireNonNull(collection);
1 ✔
3689
      if (collection != this) {
1 ✔
3690
        for (Object o : collection) {
1 ✔
3691
          if ((o == null) || !contains(o)) {
1 ✔
3692
            return false;
1 ✔
3693
          }
3694
        }
1 ✔
3695
      }
3696
      return true;
1 ✔
3697
    }
3698

3699
    @Override
3700
    public boolean removeAll(Collection<?> collection) {
3701
      requireNonNull(collection);
1 ✔
3702
      @Var boolean modified = false;
1 ✔
3703
      if (cache.collectKeys() || ((collection instanceof Set<?>) && (collection.size() > size()))) {
1 ✔
3704
        for (K key : this) {
1 ✔
3705
          if (collection.contains(key)) {
1 ✔
3706
            modified |= remove(key);
1 ✔
3707
          }
3708
        }
1 ✔
3709
      } else {
3710
        for (var item : collection) {
1 ✔
3711
          modified |= (item != null) && remove(item);
1 ✔
3712
        }
1 ✔
3713
      }
3714
      return modified;
1 ✔
3715
    }
3716

3717
    @Override
3718
    public boolean remove(@Nullable Object o) {
3719
      return (cache.remove(o) != null);
1 ✔
3720
    }
3721

3722
    @Override
3723
    public boolean removeIf(Predicate<? super K> filter) {
3724
      requireNonNull(filter);
1 ✔
3725
      @Var boolean modified = false;
1 ✔
3726
      for (K key : this) {
1 ✔
3727
        if (filter.test(key) && remove(key)) {
1 ✔
3728
          modified = true;
1 ✔
3729
        }
3730
      }
1 ✔
3731
      return modified;
1 ✔
3732
    }
3733

3734
    @Override
3735
    public boolean retainAll(Collection<?> collection) {
3736
      requireNonNull(collection);
1 ✔
3737
      @Var boolean modified = false;
1 ✔
3738
      for (K key : this) {
1 ✔
3739
        if (!collection.contains(key) && remove(key)) {
1 ✔
3740
          modified = true;
1 ✔
3741
        }
3742
      }
1 ✔
3743
      return modified;
1 ✔
3744
    }
3745

3746
    @Override
3747
    public Iterator<K> iterator() {
3748
      return new KeyIterator<>(cache);
1 ✔
3749
    }
3750

3751
    @Override
3752
    public Spliterator<K> spliterator() {
3753
      return new KeySpliterator<>(cache);
1 ✔
3754
    }
3755
  }
3756

3757
  /** An adapter to safely externalize the key iterator. */
3758
  static final class KeyIterator<K, V> implements Iterator<K> {
3759
    final EntryIterator<K, V> iterator;
3760

3761
    KeyIterator(BoundedLocalCache<K, V> cache) {
1 ✔
3762
      this.iterator = new EntryIterator<>(cache);
1 ✔
3763
    }
1 ✔
3764

3765
    @Override
3766
    public boolean hasNext() {
3767
      return iterator.hasNext();
1 ✔
3768
    }
3769

3770
    @Override
3771
    public K next() {
3772
      return iterator.nextKey();
1 ✔
3773
    }
3774

3775
    @Override
3776
    public void remove() {
3777
      iterator.remove();
1 ✔
3778
    }
1 ✔
3779
  }
3780

3781
  /** An adapter to safely externalize the key spliterator. */
3782
  static final class KeySpliterator<K, V> implements Spliterator<K> {
3783
    final Spliterator<Node<K, V>> spliterator;
3784
    final BoundedLocalCache<K, V> cache;
3785

3786
    KeySpliterator(BoundedLocalCache<K, V> cache) {
3787
      this(cache, cache.data.values().spliterator());
1 ✔
3788
    }
1 ✔
3789

3790
    KeySpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1 ✔
3791
      this.spliterator = requireNonNull(spliterator);
1 ✔
3792
      this.cache = requireNonNull(cache);
1 ✔
3793
    }
1 ✔
3794

3795
    @Override
3796
    public void forEachRemaining(Consumer<? super K> action) {
3797
      requireNonNull(action);
1 ✔
3798
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
3799
        long now = cache.expirationTicker().read();
1 ✔
3800
        boolean expired = cache.hasExpired(node, now);
1 ✔
3801
        K key = node.getKey();
1 ✔
3802
        V value = node.getValue();
1 ✔
3803
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
3804
          cache.scheduleDrainBuffers();
1 ✔
3805
        } else if (node.isAlive()) {
1 ✔
3806
          action.accept(key);
1 ✔
3807
        }
3808
      };
1 ✔
3809
      spliterator.forEachRemaining(consumer);
1 ✔
3810
    }
1 ✔
3811

3812
    @Override
3813
    public boolean tryAdvance(Consumer<? super K> action) {
3814
      requireNonNull(action);
1 ✔
3815
      boolean[] advanced = { false };
1 ✔
3816
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
3817
        long now = cache.expirationTicker().read();
1 ✔
3818
        boolean expired = cache.hasExpired(node, now);
1 ✔
3819
        K key = node.getKey();
1 ✔
3820
        V value = node.getValue();
1 ✔
3821
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
3822
          cache.scheduleDrainBuffers();
1 ✔
3823
        } else if (node.isAlive()) {
1 ✔
3824
          action.accept(key);
1 ✔
3825
          advanced[0] = true;
1 ✔
3826
        }
3827
      };
1 ✔
3828
      while (spliterator.tryAdvance(consumer)) {
1 ✔
3829
        if (advanced[0]) {
1 ✔
3830
          return true;
1 ✔
3831
        }
3832
      }
3833
      return false;
1 ✔
3834
    }
3835

3836
    @Override
3837
    public @Nullable Spliterator<K> trySplit() {
3838
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1 ✔
3839
      return (split == null) ? null : new KeySpliterator<>(cache, split);
1 ✔
3840
    }
3841

3842
    @Override
3843
    public long estimateSize() {
3844
      return spliterator.estimateSize();
1 ✔
3845
    }
3846

3847
    @Override
3848
    public int characteristics() {
3849
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
3850
    }
3851
  }
3852

3853
  /** An adapter to safely externalize the values. */
3854
  static final class ValuesView<K, V> extends AbstractCollection<V> {
3855
    final BoundedLocalCache<K, V> cache;
3856

3857
    ValuesView(BoundedLocalCache<K, V> cache) {
1 ✔
3858
      this.cache = requireNonNull(cache);
1 ✔
3859
    }
1 ✔
3860

3861
    @Override
3862
    public int size() {
3863
      return cache.size();
1 ✔
3864
    }
3865

3866
    @Override
3867
    public void clear() {
3868
      cache.clear();
1 ✔
3869
    }
1 ✔
3870

3871
    @Override
3872
    @SuppressWarnings("SuspiciousMethodCalls")
3873
    public boolean contains(@Nullable Object o) {
3874
      return cache.containsValue(o);
1 ✔
3875
    }
3876

3877
    @Override
3878
    public boolean containsAll(Collection<?> collection) {
3879
      requireNonNull(collection);
1 ✔
3880
      if (collection != this) {
1 ✔
3881
        for (Object o : collection) {
1 ✔
3882
          if ((o == null) || !contains(o)) {
1 ✔
3883
            return false;
1 ✔
3884
          }
3885
        }
1 ✔
3886
      }
3887
      return true;
1 ✔
3888
    }
3889

3890
    @Override
3891
    public boolean removeAll(Collection<?> collection) {
3892
      requireNonNull(collection);
1 ✔
3893
      @Var boolean modified = false;
1 ✔
3894
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1 ✔
3895
        var key = requireNonNull(iterator.key);
1 ✔
3896
        var value = requireNonNull(iterator.value);
1 ✔
3897
        if (collection.contains(value) && cache.remove(key, value)) {
1 ✔
3898
          modified = true;
1 ✔
3899
        }
3900
        iterator.advance();
1 ✔
3901
      }
1 ✔
3902
      return modified;
1 ✔
3903
    }
3904

3905
    @Override
3906
    public boolean remove(@Nullable Object o) {
3907
      if (o == null) {
1 ✔
3908
        return false;
1 ✔
3909
      }
3910
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1 ✔
3911
        var key = requireNonNull(iterator.key);
1 ✔
3912
        var node = requireNonNull(iterator.next);
1 ✔
3913
        var value = requireNonNull(iterator.value);
1 ✔
3914
        if (node.containsValue(o) && cache.remove(key, value)) {
1 ✔
3915
          return true;
1 ✔
3916
        }
3917
        iterator.advance();
1 ✔
3918
      }
1 ✔
3919
      return false;
1 ✔
3920
    }
3921

3922
    @Override
3923
    public boolean removeIf(Predicate<? super V> filter) {
3924
      requireNonNull(filter);
1 ✔
3925
      @Var boolean modified = false;
1 ✔
3926
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1 ✔
3927
        var value = requireNonNull(iterator.value);
1 ✔
3928
        if (filter.test(value)) {
1 ✔
3929
          var key = requireNonNull(iterator.key);
1 ✔
3930
          modified |= cache.remove(key, value);
1 ✔
3931
        }
3932
        iterator.advance();
1 ✔
3933
      }
1 ✔
3934
      return modified;
1 ✔
3935
    }
3936

3937
    @Override
3938
    public boolean retainAll(Collection<?> collection) {
3939
      requireNonNull(collection);
1 ✔
3940
      @Var boolean modified = false;
1 ✔
3941
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1 ✔
3942
        var key = requireNonNull(iterator.key);
1 ✔
3943
        var value = requireNonNull(iterator.value);
1 ✔
3944
        if (!collection.contains(value) && cache.remove(key, value)) {
1 ✔
3945
          modified = true;
1 ✔
3946
        }
3947
        iterator.advance();
1 ✔
3948
      }
1 ✔
3949
      return modified;
1 ✔
3950
    }
3951

3952
    @Override
3953
    public Iterator<V> iterator() {
3954
      return new ValueIterator<>(cache);
1 ✔
3955
    }
3956

3957
    @Override
3958
    public Spliterator<V> spliterator() {
3959
      return new ValueSpliterator<>(cache);
1 ✔
3960
    }
3961
  }
3962

3963
  /** An adapter to safely externalize the value iterator. */
3964
  static final class ValueIterator<K, V> implements Iterator<V> {
3965
    final EntryIterator<K, V> iterator;
3966

3967
    ValueIterator(BoundedLocalCache<K, V> cache) {
1 ✔
3968
      this.iterator = new EntryIterator<>(cache);
1 ✔
3969
    }
1 ✔
3970

3971
    @Override
3972
    public boolean hasNext() {
3973
      return iterator.hasNext();
1 ✔
3974
    }
3975

3976
    @Override
3977
    public V next() {
3978
      return iterator.nextValue();
1 ✔
3979
    }
3980

3981
    @Override
3982
    public void remove() {
3983
      iterator.remove();
1 ✔
3984
    }
1 ✔
3985
  }
3986

3987
  /** An adapter to safely externalize the value spliterator. */
3988
  static final class ValueSpliterator<K, V> implements Spliterator<V> {
3989
    final Spliterator<Node<K, V>> spliterator;
3990
    final BoundedLocalCache<K, V> cache;
3991

3992
    ValueSpliterator(BoundedLocalCache<K, V> cache) {
3993
      this(cache, cache.data.values().spliterator());
1 ✔
3994
    }
1 ✔
3995

3996
    ValueSpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1 ✔
3997
      this.spliterator = requireNonNull(spliterator);
1 ✔
3998
      this.cache = requireNonNull(cache);
1 ✔
3999
    }
1 ✔
4000

4001
    @Override
4002
    public void forEachRemaining(Consumer<? super V> action) {
4003
      requireNonNull(action);
1 ✔
4004
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
4005
        long now = cache.expirationTicker().read();
1 ✔
4006
        boolean expired = cache.hasExpired(node, now);
1 ✔
4007
        K key = node.getKey();
1 ✔
4008
        V value = node.getValue();
1 ✔
4009
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
4010
          cache.scheduleDrainBuffers();
1 ✔
4011
        } else if (node.isAlive()) {
1 ✔
4012
          action.accept(value);
1 ✔
4013
        }
4014
      };
1 ✔
4015
      spliterator.forEachRemaining(consumer);
1 ✔
4016
    }
1 ✔
4017

4018
    @Override
4019
    public boolean tryAdvance(Consumer<? super V> action) {
4020
      requireNonNull(action);
1 ✔
4021
      boolean[] advanced = { false };
1 ✔
4022
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
4023
        long now = cache.expirationTicker().read();
1 ✔
4024
        boolean expired = cache.hasExpired(node, now);
1 ✔
4025
        K key = node.getKey();
1 ✔
4026
        V value = node.getValue();
1 ✔
4027
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
4028
          cache.scheduleDrainBuffers();
1 ✔
4029
        } else if (node.isAlive()) {
1 ✔
4030
          action.accept(value);
1 ✔
4031
          advanced[0] = true;
1 ✔
4032
        }
4033
      };
1 ✔
4034
      while (spliterator.tryAdvance(consumer)) {
1 ✔
4035
        if (advanced[0]) {
1 ✔
4036
          return true;
1 ✔
4037
        }
4038
      }
4039
      return false;
1 ✔
4040
    }
4041

4042
    @Override
4043
    public @Nullable Spliterator<V> trySplit() {
4044
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1 ✔
4045
      return (split == null) ? null : new ValueSpliterator<>(cache, split);
1 ✔
4046
    }
4047

4048
    @Override
4049
    public long estimateSize() {
4050
      return spliterator.estimateSize();
1 ✔
4051
    }
4052

4053
    @Override
4054
    public int characteristics() {
4055
      return CONCURRENT | NONNULL;
1 ✔
4056
    }
4057
  }
4058

4059
  /** An adapter to safely externalize the entries. */
4060
  static final class EntrySetView<K, V> extends AbstractSet<Entry<K, V>> {
4061
    final BoundedLocalCache<K, V> cache;
4062

4063
    EntrySetView(BoundedLocalCache<K, V> cache) {
1 ✔
4064
      this.cache = requireNonNull(cache);
1 ✔
4065
    }
1 ✔
4066

4067
    @Override
4068
    public int size() {
4069
      return cache.size();
1 ✔
4070
    }
4071

4072
    @Override
4073
    public void clear() {
4074
      cache.clear();
1 ✔
4075
    }
1 ✔
4076

4077
    @Override
4078
    public boolean contains(@Nullable Object o) {
4079
      if (!(o instanceof Entry<?, ?>)) {
1 ✔
4080
        return false;
1 ✔
4081
      }
4082
      var entry = (Entry<?, ?>) o;
1 ✔
4083
      var key = entry.getKey();
1 ✔
4084
      var value = entry.getValue();
1 ✔
4085
      if ((key == null) || (value == null)) {
1 ✔
4086
        return false;
1 ✔
4087
      }
4088
      Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1 ✔
4089
      if (node == null) {
1 ✔
4090
        return false;
1 ✔
4091
      }
4092
      boolean expired = cache.hasExpired(node, cache.expirationTicker().read());
1 ✔
4093
      V nodeValue = node.getValue();
1 ✔
4094
      return (nodeValue != null) && node.containsValue(value)
1 ✔
4095
          && (!expired || cache.isComputingAsync(nodeValue));
1 ✔
4096
    }
4097

4098
    @Override
4099
    public boolean containsAll(Collection<?> collection) {
4100
      requireNonNull(collection);
1 ✔
4101
      if (collection != this) {
1 ✔
4102
        for (Object o : collection) {
1 ✔
4103
          if ((o == null) || !contains(o)) {
1 ✔
4104
            return false;
1 ✔
4105
          }
4106
        }
1 ✔
4107
      }
4108
      return true;
1 ✔
4109
    }
4110

4111
    @Override
4112
    public boolean removeAll(Collection<?> collection) {
4113
      requireNonNull(collection);
1 ✔
4114
      @Var boolean modified = false;
1 ✔
4115
      if (cache.collectKeys() || cache.collectValues()
1 ✔
4116
          || ((collection instanceof Set<?>) && (collection.size() > size()))) {
1 ✔
4117
        for (var entry : this) {
1 ✔
4118
          if (collection.contains(entry)) {
1 ✔
4119
            modified |= remove(entry);
1 ✔
4120
          }
4121
        }
1 ✔
4122
      } else {
4123
        for (var item : collection) {
1 ✔
4124
          modified |= remove(item);
1 ✔
4125
        }
1 ✔
4126
      }
4127
      return modified;
1 ✔
4128
    }
4129

4130
    @Override
4131
    @SuppressWarnings("SuspiciousMethodCalls")
4132
    public boolean remove(@Nullable Object o) {
4133
      if (!(o instanceof Entry<?, ?>)) {
1 ✔
4134
        return false;
1 ✔
4135
      }
4136
      var entry = (Entry<?, ?>) o;
1 ✔
4137
      var key = entry.getKey();
1 ✔
4138
      return (key != null) && cache.remove(key, entry.getValue());
1 ✔
4139
    }
4140

4141
    @Override
4142
    public boolean removeIf(Predicate<? super Entry<K, V>> filter) {
4143
      requireNonNull(filter);
1 ✔
4144
      @Var boolean modified = false;
1 ✔
4145
      for (var iterator = new EntryIterator<>(cache); iterator.hasNext();) {
1 ✔
4146
        var key = requireNonNull(iterator.key);
1 ✔
4147
        var value = requireNonNull(iterator.value);
1 ✔
4148
        if (filter.test(Map.entry(key, value))) {
1 ✔
4149
          modified |= cache.remove(key, value);
1 ✔
4150
        }
4151
        iterator.advance();
1 ✔
4152
      }
1 ✔
4153
      return modified;
1 ✔
4154
    }
4155

4156
    @Override
4157
    public boolean retainAll(Collection<?> collection) {
4158
      requireNonNull(collection);
1 ✔
4159
      @Var boolean modified = false;
1 ✔
4160
      for (var entry : this) {
1 ✔
4161
        if (!collection.contains(entry) && remove(entry)) {
1 ✔
4162
          modified = true;
1 ✔
4163
        }
4164
      }
1 ✔
4165
      return modified;
1 ✔
4166
    }
4167

4168
    @Override
4169
    public Iterator<Entry<K, V>> iterator() {
4170
      return new EntryIterator<>(cache);
1 ✔
4171
    }
4172

4173
    @Override
4174
    public Spliterator<Entry<K, V>> spliterator() {
4175
      return new EntrySpliterator<>(cache);
1 ✔
4176
    }
4177
  }
4178

4179
  /** An adapter to safely externalize the entry iterator. */
4180
  static final class EntryIterator<K, V> implements Iterator<Entry<K, V>> {
4181
    final BoundedLocalCache<K, V> cache;
4182
    final Iterator<Node<K, V>> iterator;
4183

4184
    @Nullable K key;
4185
    @Nullable V value;
4186
    @Nullable K removalKey;
4187
    @Nullable Node<K, V> next;
4188

4189
    EntryIterator(BoundedLocalCache<K, V> cache) {
1 ✔
4190
      this.iterator = cache.data.values().iterator();
1 ✔
4191
      this.cache = cache;
1 ✔
4192
    }
1 ✔
4193

4194
    @Override
4195
    public boolean hasNext() {
4196
      if (next != null) {
1 ✔
4197
        return true;
1 ✔
4198
      }
4199

4200
      long now = cache.expirationTicker().read();
1 ✔
4201
      while (iterator.hasNext()) {
1 ✔
4202
        next = iterator.next();
1 ✔
4203
        boolean expired = cache.hasExpired(next, now);
1 ✔
4204
        value = next.getValue();
1 ✔
4205
        key = next.getKey();
1 ✔
4206

4207
        boolean evictable = (key == null) || (value == null)
1 ✔
4208
            || (expired && !cache.isComputingAsync(value));
1 ✔
4209
        if (evictable || !next.isAlive()) {
1 ✔
4210
          if (evictable) {
1 ✔
4211
            cache.scheduleDrainBuffers();
1 ✔
4212
          }
4213
          advance();
1 ✔
4214
          continue;
1 ✔
4215
        }
4216
        return true;
1 ✔
4217
      }
4218
      return false;
1 ✔
4219
    }
4220

4221
    /** Invalidates the current position so that the iterator may compute the next position. */
4222
    void advance() {
4223
      value = null;
1 ✔
4224
      next = null;
1 ✔
4225
      key = null;
1 ✔
4226
    }
1 ✔
4227

4228
    K nextKey() {
4229
      if (!hasNext()) {
1 ✔
4230
        throw new NoSuchElementException();
1 ✔
4231
      }
4232
      removalKey = key;
1 ✔
4233
      advance();
1 ✔
4234
      return requireNonNull(removalKey);
1 ✔
4235
    }
4236

4237
    V nextValue() {
4238
      if (!hasNext()) {
1 ✔
4239
        throw new NoSuchElementException();
1 ✔
4240
      }
4241
      removalKey = key;
1 ✔
4242
      V val = value;
1 ✔
4243
      advance();
1 ✔
4244
      return requireNonNull(val);
1 ✔
4245
    }
4246

4247
    @Override
4248
    public Entry<K, V> next() {
4249
      if (!hasNext()) {
1 ✔
4250
        throw new NoSuchElementException();
1 ✔
4251
      }
4252
      var entry = new WriteThroughEntry<K, @NonNull V>(
1 ✔
4253
          cache, requireNonNull(key), requireNonNull(value));
1 ✔
4254
      removalKey = key;
1 ✔
4255
      advance();
1 ✔
4256
      return entry;
1 ✔
4257
    }
4258

4259
    @Override
4260
    public void remove() {
4261
      if (removalKey == null) {
1 ✔
4262
        throw new IllegalStateException();
1 ✔
4263
      }
4264
      cache.remove(removalKey);
1 ✔
4265
      removalKey = null;
1 ✔
4266
    }
1 ✔
4267
  }
4268

4269
  /** An adapter to safely externalize the entry spliterator. */
4270
  static final class EntrySpliterator<K, V> implements Spliterator<Entry<K, V>> {
4271
    final Spliterator<Node<K, V>> spliterator;
4272
    final BoundedLocalCache<K, V> cache;
4273

4274
    EntrySpliterator(BoundedLocalCache<K, V> cache) {
4275
      this(cache, cache.data.values().spliterator());
1 ✔
4276
    }
1 ✔
4277

4278
    EntrySpliterator(BoundedLocalCache<K, V> cache, Spliterator<Node<K, V>> spliterator) {
1 ✔
4279
      this.spliterator = requireNonNull(spliterator);
1 ✔
4280
      this.cache = requireNonNull(cache);
1 ✔
4281
    }
1 ✔
4282

4283
    @Override
4284
    public void forEachRemaining(Consumer<? super Entry<K, V>> action) {
4285
      requireNonNull(action);
1 ✔
4286
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
4287
        long now = cache.expirationTicker().read();
1 ✔
4288
        boolean expired = cache.hasExpired(node, now);
1 ✔
4289
        K key = node.getKey();
1 ✔
4290
        V value = node.getValue();
1 ✔
4291
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
4292
          cache.scheduleDrainBuffers();
1 ✔
4293
        } else if (node.isAlive()) {
1 ✔
4294
          action.accept(new WriteThroughEntry<>(cache, key, value));
1 ✔
4295
        }
4296
      };
1 ✔
4297
      spliterator.forEachRemaining(consumer);
1 ✔
4298
    }
1 ✔
4299

4300
    @Override
4301
    public boolean tryAdvance(Consumer<? super Entry<K, V>> action) {
4302
      requireNonNull(action);
1 ✔
4303
      boolean[] advanced = { false };
1 ✔
4304
      Consumer<Node<K, V>> consumer = node -> {
1 ✔
4305
        long now = cache.expirationTicker().read();
1 ✔
4306
        boolean expired = cache.hasExpired(node, now);
1 ✔
4307
        K key = node.getKey();
1 ✔
4308
        V value = node.getValue();
1 ✔
4309
        if ((key == null) || (value == null) || (expired && !cache.isComputingAsync(value))) {
1 ✔
4310
          cache.scheduleDrainBuffers();
1 ✔
4311
        } else if (node.isAlive()) {
1 ✔
4312
          action.accept(new WriteThroughEntry<>(cache, key, value));
1 ✔
4313
          advanced[0] = true;
1 ✔
4314
        }
4315
      };
1 ✔
4316
      while (spliterator.tryAdvance(consumer)) {
1 ✔
4317
        if (advanced[0]) {
1 ✔
4318
          return true;
1 ✔
4319
        }
4320
      }
4321
      return false;
1 ✔
4322
    }
4323

4324
    @Override
4325
    public @Nullable Spliterator<Entry<K, V>> trySplit() {
4326
      Spliterator<Node<K, V>> split = spliterator.trySplit();
1 ✔
4327
      return (split == null) ? null : new EntrySpliterator<>(cache, split);
1 ✔
4328
    }
4329

4330
    @Override
4331
    public long estimateSize() {
4332
      return spliterator.estimateSize();
1 ✔
4333
    }
4334

4335
    @Override
4336
    public int characteristics() {
4337
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
4338
    }
4339
  }
4340

4341
  /** A reusable task that performs the maintenance work. */
4342
  static final class PerformCleanupTask
4343
      extends WeakReference<BoundedLocalCache<?, ?>> implements Runnable {
4344

4345
    PerformCleanupTask(BoundedLocalCache<?, ?> cache) {
4346
      super(cache);
1 ✔
4347
    }
1 ✔
4348

4349
    @Override
4350
    public void run() {
4351
      BoundedLocalCache<?, ?> cache = get();
1 ✔
4352
      // A thread waiting for the lock performs the maintenance, so a copy need not queue behind it
4353
      if ((cache != null) && !cache.isEvictionLockAwaited()) {
1 ✔
4354
        try {
4355
          cache.performCleanUp(/* ignored */ null);
1 ✔
4356
        } catch (Throwable t) {
1 ✔
4357
          logger.log(Level.ERROR, "Exception thrown when performing the maintenance task", t);
1 ✔
4358
        }
1 ✔
4359
      }
4360
    }
1 ✔
4361
    @Override public void clear() {}
1 ✔
4362
    @Override public boolean enqueue() {
4363
      return false;
1 ✔
4364
    }
4365
  }
4366

4367
  /* --------------- Manual Cache --------------- */
4368

4369
  static class BoundedLocalManualCache<K, V> implements LocalManualCache<K, V>, Serializable {
4370
    private static final long serialVersionUID = 1;
4371

4372
    final BoundedLocalCache<K, V> cache;
4373

4374
    @Nullable Policy<K, V> policy;
4375

4376
    BoundedLocalManualCache(Caffeine<K, V> builder) {
4377
      this(builder, null);
1 ✔
4378
    }
1 ✔
4379

4380
    BoundedLocalManualCache(Caffeine<K, V> builder, @Nullable CacheLoader<? super K, V> loader) {
1 ✔
4381
      cache = LocalCacheFactory.newBoundedLocalCache(builder, loader, /* isAsync= */ false);
1 ✔
4382
    }
1 ✔
4383

4384
    @Override
4385
    public final BoundedLocalCache<K, V> cache() {
4386
      return cache;
1 ✔
4387
    }
4388

4389
    @Override
4390
    public final Policy<K, V> policy() {
4391
      @Var var p = policy;
1 ✔
4392
      if (p == null) {
1 ✔
4393
        Function<@Nullable V, @Nullable V> identity = v -> v;
1 ✔
4394
        p = new BoundedPolicy<>(cache, identity);
1 ✔
4395
        policy = p;
1 ✔
4396
      }
4397
      return p;
1 ✔
4398
    }
4399

4400
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4401
      throw new InvalidObjectException("Proxy required");
1 ✔
4402
    }
4403

4404
    private Object writeReplace() {
4405
      return makeSerializationProxy(cache);
1 ✔
4406
    }
4407
  }
4408

4409
  @SuppressWarnings({"NullableOptional",
4410
    "OptionalAssignedToNull", "OptionalUsedAsFieldOrParameterType"})
4411
  static final class BoundedPolicy<K, V> implements Policy<K, V> {
4412
    final Function<@Nullable V, @Nullable V> transformer;
4413
    final BoundedLocalCache<K, V> cache;
4414

4415
    @Nullable Optional<Eviction<K, V>> eviction;
4416
    @Nullable Optional<FixedRefresh<K, V>> refreshes;
4417
    @Nullable Optional<FixedExpiration<K, V>> afterWrite;
4418
    @Nullable Optional<FixedExpiration<K, V>> afterAccess;
4419
    @Nullable Optional<VarExpiration<K, V>> variable;
4420

4421
    BoundedPolicy(BoundedLocalCache<K, V> cache, Function<@Nullable V, @Nullable V> transformer) {
1 ✔
4422
      this.transformer = transformer;
1 ✔
4423
      this.cache = cache;
1 ✔
4424
    }
1 ✔
4425

4426
    @Override public boolean isRecordingStats() {
4427
      return cache.isRecordingStats();
1 ✔
4428
    }
4429
    @Override public @Nullable V getIfPresentQuietly(K key) {
4430
      return transformer.apply(cache.getIfPresentQuietly(key));
1 ✔
4431
    }
4432
    @SuppressWarnings("GuardedByChecker")
4433
    @Override public @Nullable CacheEntry<K, V> getEntryIfPresentQuietly(K key) {
4434
      Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1 ✔
4435
      return (node == null) ? null : cache.nodeToCacheEntry(node, transformer, node.getWeight());
1 ✔
4436
    }
4437
    @SuppressWarnings("Java9CollectionFactory")
4438
    @Override public Map<K, CompletableFuture<V>> refreshes() {
4439
      var refreshes = cache.refreshes;
1 ✔
4440
      if ((refreshes == null) || refreshes.isEmpty()) {
1 ✔
4441
        @SuppressWarnings({"ImmutableMapOf", "RedundantUnmodifiable"})
4442
        Map<K, CompletableFuture<V>> emptyMap = Collections.unmodifiableMap(Collections.emptyMap());
1 ✔
4443
        return emptyMap;
1 ✔
4444
      } else if (cache.collectKeys()) {
1 ✔
4445
        var inFlight = new IdentityHashMap<K, CompletableFuture<V>>(refreshes.size());
1 ✔
4446
        for (var entry : refreshes.entrySet()) {
1 ✔
4447
          @SuppressWarnings("unchecked")
4448
          var key = ((InternalReference<K>) entry.getKey()).get();
1 ✔
4449
          @SuppressWarnings("unchecked")
4450
          var future = (CompletableFuture<V>) entry.getValue();
1 ✔
4451
          if ((key != null) && !(future instanceof LocalLoadingCache.PendingRefresh)) {
1 ✔
4452
            inFlight.put(key, future);
1 ✔
4453
          }
4454
        }
1 ✔
4455
        return Collections.unmodifiableMap(inFlight);
1 ✔
4456
      }
4457
      @SuppressWarnings("unchecked")
4458
      var castedRefreshes = (Map<K, CompletableFuture<V>>) (Object) refreshes;
1 ✔
4459
      var inFlight = new HashMap<>(castedRefreshes);
1 ✔
4460
      inFlight.values().removeIf(LocalLoadingCache.PendingRefresh.class::isInstance);
1 ✔
4461
      return Collections.unmodifiableMap(inFlight);
1 ✔
4462
    }
4463
    @Override public Optional<Eviction<K, V>> eviction() {
4464
      if (!cache.evicts()) {
1 ✔
4465
        return Optional.empty();
1 ✔
4466
      }
4467
      var e = eviction;
1 ✔
4468
      return (e == null) ? (eviction = Optional.of(new BoundedEviction())) : e;
1 ✔
4469
    }
4470
    @Override public Optional<FixedExpiration<K, V>> expireAfterAccess() {
4471
      if (!cache.expiresAfterAccess()) {
1 ✔
4472
        return Optional.empty();
1 ✔
4473
      }
4474
      var e = afterAccess;
1 ✔
4475
      return (e == null)
1 ✔
4476
          ? (afterAccess = Optional.of(new BoundedExpireAfterAccess()))
1 ✔
4477
          : e;
1 ✔
4478
    }
4479
    @Override public Optional<FixedExpiration<K, V>> expireAfterWrite() {
4480
      if (!cache.expiresAfterWrite()) {
1 ✔
4481
        return Optional.empty();
1 ✔
4482
      }
4483
      var e = afterWrite;
1 ✔
4484
      return (e == null)
1 ✔
4485
          ? (afterWrite = Optional.of(new BoundedExpireAfterWrite()))
1 ✔
4486
          : e;
1 ✔
4487
    }
4488
    @Override public Optional<VarExpiration<K, V>> expireVariably() {
4489
      if (!cache.expiresVariable()) {
1 ✔
4490
        return Optional.empty();
1 ✔
4491
      }
4492
      var e = variable;
1 ✔
4493
      return (e == null)
1 ✔
4494
          ? (variable = Optional.of(new BoundedVarExpiration()))
1 ✔
4495
          : e;
1 ✔
4496
    }
4497
    @Override public Optional<FixedRefresh<K, V>> refreshAfterWrite() {
4498
      if (!cache.refreshAfterWrite()) {
1 ✔
4499
        return Optional.empty();
1 ✔
4500
      }
4501
      var r = refreshes;
1 ✔
4502
      return (r == null)
1 ✔
4503
          ? (refreshes = Optional.of(new BoundedRefreshAfterWrite()))
1 ✔
4504
          : r;
1 ✔
4505
    }
4506

4507
    final class BoundedEviction implements Eviction<K, V> {
1 ✔
4508
      @Override public boolean isWeighted() {
4509
        return cache.isWeighted;
1 ✔
4510
      }
4511
      @Override public OptionalInt weightOf(K key) {
4512
        requireNonNull(key);
1 ✔
4513
        if (!cache.isWeighted) {
1 ✔
4514
          return OptionalInt.empty();
1 ✔
4515
        }
4516
        Node<K, V> node = cache.data.get(cache.nodeFactory.newLookupKey(key));
1 ✔
4517
        if (node == null) {
1 ✔
4518
          return OptionalInt.empty();
1 ✔
4519
        }
4520
        boolean expired = cache.hasExpired(node, cache.expirationTicker().read());
1 ✔
4521
        if (expired) {
1 ✔
4522
          return OptionalInt.empty();
1 ✔
4523
        }
4524
        synchronized (node) {
1 ✔
4525
          V value = node.getValue();
1 ✔
4526
          return ((value != null) && node.isAlive() && !cache.isComputingAsync(value))
1 ✔
4527
              ? OptionalInt.of(node.getWeight())
1 ✔
4528
              : OptionalInt.empty();
1 ✔
4529
        }
4530
      }
4531
      @Override public OptionalLong weightedSize() {
4532
        return cache.isWeighted
1 ✔
4533
            ? OptionalLong.of(Math.max(0, cache.weightedSizeAcquire()))
1 ✔
4534
            : OptionalLong.empty();
1 ✔
4535
      }
4536
      @Override public long getMaximum() {
4537
        return cache.maximumAcquire();
1 ✔
4538
      }
4539
      @Override public void setMaximum(long maximum) {
4540
        requireArgument(maximum >= 0, "maximum must not be negative");
1 ✔
4541
        cache.evictionLock.lock();
1 ✔
4542
        try {
4543
          cache.setMaximumSize(maximum);
1 ✔
4544
          cache.maintenance(/* ignored */ null);
1 ✔
4545
        } finally {
4546
          cache.evictionLock.unlock();
1 ✔
4547
          cache.rescheduleCleanUpIfIncomplete();
1 ✔
4548
        }
4549
      }
1 ✔
4550
      @Override public Map<K, V> coldest(int limit) {
4551
        int expectedSize = Math.min(limit, cache.size());
1 ✔
4552
        var limiter = new SizeLimiter<K, V>(expectedSize, limit);
1 ✔
4553
        return cache.evictionOrder(/* hottest= */ false, transformer, limiter);
1 ✔
4554
      }
4555
      @Override public Map<K, V> coldestWeighted(long weightLimit) {
4556
        var limiter = isWeighted()
1 ✔
4557
            ? new WeightLimiter<K, V>(weightLimit)
1 ✔
4558
            : new SizeLimiter<K, V>((int) Math.min(weightLimit, cache.size()), weightLimit);
1 ✔
4559
        return cache.evictionOrder(/* hottest= */ false, transformer, limiter);
1 ✔
4560
      }
4561
      @Override
4562
      public <T extends @Nullable Object> T coldest(
4563
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4564
        requireNonNull(mappingFunction);
1 ✔
4565
        return cache.evictionOrder(/* hottest= */ false, transformer, mappingFunction);
1 ✔
4566
      }
4567
      @Override public Map<K, V> hottest(int limit) {
4568
        int expectedSize = Math.min(limit, cache.size());
1 ✔
4569
        var limiter = new SizeLimiter<K, V>(expectedSize, limit);
1 ✔
4570
        return cache.evictionOrder(/* hottest= */ true, transformer, limiter);
1 ✔
4571
      }
4572
      @Override public Map<K, V> hottestWeighted(long weightLimit) {
4573
        var limiter = isWeighted()
1 ✔
4574
            ? new WeightLimiter<K, V>(weightLimit)
1 ✔
4575
            : new SizeLimiter<K, V>((int) Math.min(weightLimit, cache.size()), weightLimit);
1 ✔
4576
        return cache.evictionOrder(/* hottest= */ true, transformer, limiter);
1 ✔
4577
      }
4578
      @Override
4579
      public <T extends @Nullable Object> T hottest(
4580
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4581
        requireNonNull(mappingFunction);
1 ✔
4582
        return cache.evictionOrder(/* hottest= */ true, transformer, mappingFunction);
1 ✔
4583
      }
4584
    }
4585

4586
    @SuppressWarnings("PreferJavaTimeOverload")
4587
    final class BoundedExpireAfterAccess implements FixedExpiration<K, V> {
1 ✔
4588
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4589
        requireNonNull(key);
1 ✔
4590
        requireNonNull(unit);
1 ✔
4591
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1 ✔
4592
        Node<K, V> node = cache.data.get(lookupKey);
1 ✔
4593
        if (node == null) {
1 ✔
4594
          return OptionalLong.empty();
1 ✔
4595
        }
4596
        long now = cache.expirationTicker().read();
1 ✔
4597
        boolean expired = cache.hasExpired(node, now);
1 ✔
4598
        V value = node.getValue();
1 ✔
4599
        if ((value == null) || expired || cache.isComputingAsync(value)) {
1 ✔
4600
          return OptionalLong.empty();
1 ✔
4601
        }
4602
        long age = now - node.getAccessTime();
1 ✔
4603
        return (age < 0)
1 ✔
4604
            ? OptionalLong.empty()
1 ✔
4605
            : OptionalLong.of(unit.convert(age, TimeUnit.NANOSECONDS));
1 ✔
4606
      }
4607
      @Override public long getExpiresAfter(TimeUnit unit) {
4608
        return unit.convert(cache.expiresAfterAccessNanos(), TimeUnit.NANOSECONDS);
1 ✔
4609
      }
4610
      @Override public void setExpiresAfter(long duration, TimeUnit unit) {
4611
        requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
1 ✔
4612
        cache.setExpiresAfterAccessNanos(unit.toNanos(duration));
1 ✔
4613
        cache.scheduleAfterWrite();
1 ✔
4614
      }
1 ✔
4615
      @Override public Map<K, V> oldest(int limit) {
4616
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4617
      }
4618
      @Override public <T extends @Nullable Object> T oldest(
4619
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4620
        return cache.expireAfterAccessOrder(/* oldest= */ true, transformer, mappingFunction);
1 ✔
4621
      }
4622
      @Override public Map<K, V> youngest(int limit) {
4623
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4624
      }
4625
      @Override public <T extends @Nullable Object> T youngest(
4626
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4627
        return cache.expireAfterAccessOrder(/* oldest= */ false, transformer, mappingFunction);
1 ✔
4628
      }
4629
    }
4630

4631
    @SuppressWarnings("PreferJavaTimeOverload")
4632
    final class BoundedExpireAfterWrite implements FixedExpiration<K, V> {
1 ✔
4633
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4634
        requireNonNull(key);
1 ✔
4635
        requireNonNull(unit);
1 ✔
4636
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1 ✔
4637
        Node<K, V> node = cache.data.get(lookupKey);
1 ✔
4638
        if (node == null) {
1 ✔
4639
          return OptionalLong.empty();
1 ✔
4640
        }
4641
        long now = cache.expirationTicker().read();
1 ✔
4642
        boolean expired = cache.hasExpired(node, now);
1 ✔
4643
        V value = node.getValue();
1 ✔
4644
        if ((value == null) || expired || cache.isComputingAsync(value)) {
1 ✔
4645
          return OptionalLong.empty();
1 ✔
4646
        }
4647
        long age = toWriteTime(now) - writeTimeOf(node);
1 ✔
4648
        return (age < 0)
1 ✔
4649
            ? OptionalLong.empty()
1 ✔
4650
            : OptionalLong.of(unit.convert(age, TimeUnit.NANOSECONDS));
1 ✔
4651
      }
4652
      @Override public long getExpiresAfter(TimeUnit unit) {
4653
        return unit.convert(cache.expiresAfterWriteNanos(), TimeUnit.NANOSECONDS);
1 ✔
4654
      }
4655
      @Override public void setExpiresAfter(long duration, TimeUnit unit) {
4656
        requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
1 ✔
4657
        cache.setExpiresAfterWriteNanos(unit.toNanos(duration));
1 ✔
4658
        cache.scheduleAfterWrite();
1 ✔
4659
      }
1 ✔
4660
      @Override public Map<K, V> oldest(int limit) {
4661
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4662
      }
4663
      @SuppressWarnings("GuardedByChecker")
4664
      @Override public <T extends @Nullable Object> T oldest(
4665
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4666
        return cache.snapshot(cache.writeOrderDeque(), transformer, mappingFunction);
1 ✔
4667
      }
4668
      @Override public Map<K, V> youngest(int limit) {
4669
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4670
      }
4671
      @SuppressWarnings("GuardedByChecker")
4672
      @Override public <T extends @Nullable Object> T youngest(
4673
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4674
        return cache.snapshot(cache.writeOrderDeque()::descendingIterator,
1 ✔
4675
            transformer, mappingFunction);
4676
      }
4677
    }
4678

4679
    @SuppressWarnings("PreferJavaTimeOverload")
4680
    final class BoundedVarExpiration implements VarExpiration<K, V> {
1 ✔
4681
      @Override public OptionalLong getExpiresAfter(K key, TimeUnit unit) {
4682
        requireNonNull(key);
1 ✔
4683
        requireNonNull(unit);
1 ✔
4684
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1 ✔
4685
        Node<K, V> node = cache.data.get(lookupKey);
1 ✔
4686
        if (node == null) {
1 ✔
4687
          return OptionalLong.empty();
1 ✔
4688
        }
4689
        long now = cache.expirationTicker().read();
1 ✔
4690
        boolean expired = cache.hasExpired(node, now);
1 ✔
4691
        V value = node.getValue();
1 ✔
4692
        if ((value == null) || expired || cache.isComputingAsync(value)) {
1 ✔
4693
          return OptionalLong.empty();
1 ✔
4694
        }
4695
        long duration = node.getVariableTime() - now;
1 ✔
4696
        return (cache.isAsync && (duration > MAXIMUM_EXPIRY))
1 ✔
4697
            ? OptionalLong.empty()
1 ✔
4698
            : OptionalLong.of(unit.convert(duration, TimeUnit.NANOSECONDS));
1 ✔
4699
      }
4700
      @Override public void setExpiresAfter(K key, long duration, TimeUnit unit) {
4701
        requireNonNull(key);
1 ✔
4702
        requireNonNull(unit);
1 ✔
4703
        requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
1 ✔
4704
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1 ✔
4705
        Node<K, V> node = cache.data.get(lookupKey);
1 ✔
4706
        if (node != null) {
1 ✔
4707
          long extension;
4708
          long durationNanos = TimeUnit.NANOSECONDS.convert(duration, unit);
1 ✔
4709
          synchronized (node) {
1 ✔
4710
            long now = cache.expirationTicker().read();
1 ✔
4711
            V value = node.getValue();
1 ✔
4712
            if ((value == null) || cache.isComputingAsync(value)
1 ✔
4713
                || cache.hasExpired(node, now)) {
1 ✔
4714
              return;
1 ✔
4715
            }
4716
            long expirationTime = now + Math.min(durationNanos, MAXIMUM_EXPIRY);
1 ✔
4717
            extension = expirationTime - node.getVariableTime();
1 ✔
4718
            node.setVariableTime(expirationTime);
1 ✔
4719
          }
1 ✔
4720
          if ((extension < 0) || (extension > EXPIRE_TOLERANCE)) {
1 ✔
4721
            cache.afterWrite(cache.new UpdateTask(node, 0, Access.QUIET));
1 ✔
4722
          }
4723
        }
4724
      }
1 ✔
4725
      @Override public @Nullable V put(K key, V value, long duration, TimeUnit unit) {
4726
        requireNonNull(unit);
1 ✔
4727
        requireNonNull(value);
1 ✔
4728
        requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
1 ✔
4729
        return cache.isAsync
1 ✔
4730
            ? putAsync(key, value, duration, unit)
1 ✔
4731
            : putSync(key, value, duration, unit, /* onlyIfAbsent= */ false);
1 ✔
4732
      }
4733
      @Override public @Nullable V putIfAbsent(K key, V value, long duration, TimeUnit unit) {
4734
        requireNonNull(unit);
1 ✔
4735
        requireNonNull(value);
1 ✔
4736
        requireArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
1 ✔
4737
        return cache.isAsync
1 ✔
4738
            ? putIfAbsentAsync(key, value, duration, unit)
1 ✔
4739
            : putSync(key, value, duration, unit, /* onlyIfAbsent= */ true);
1 ✔
4740
      }
4741
      @Nullable V putSync(K key, V value, long duration, TimeUnit unit, boolean onlyIfAbsent) {
4742
        var expiry = new FixedExpireAfterWrite<K, V>(duration, unit);
1 ✔
4743
        return cache.put(key, value, expiry, onlyIfAbsent);
1 ✔
4744
      }
4745
      @SuppressWarnings("unchecked")
4746
      @Nullable V putIfAbsentAsync(K key, V value, long duration, TimeUnit unit) {
4747
        // Mirrors LocalAsyncCache.AsMapView#putIfAbsent(key, value), but the first probe reads a
4748
        // present entry through the fixed duration, as putSync does, not the user's Expiry
4749
        var expiry = (Expiry<K, V>) new AsyncExpiry<>(new FixedExpireAfterWrite<>(duration, unit));
1 ✔
4750
        var asyncValue = (V) CompletableFuture.completedFuture(value);
1 ✔
4751

4752
        var probe = (CompletableFuture<V>) cache.put(
1 ✔
4753
            key, asyncValue, expiry, /* onlyIfAbsent= */ true);
4754
        V present = Async.getIfReady(probe);
1 ✔
4755
        if ((probe == null) || (present != null)) {
1 ✔
4756
          return present;
1 ✔
4757
        }
4758

4759
        for (;;) {
4760
          var priorFuture = (CompletableFuture<V>) cache.getIfPresentQuietly(key);
1 ✔
4761
          if (priorFuture != null) {
1 ✔
4762
            if (!priorFuture.isDone()) {
1 ✔
4763
              Async.getWhenSuccessful(priorFuture);
1 ✔
4764
              continue;
1 ✔
4765
            }
4766

4767
            V prior = Async.getWhenSuccessful(priorFuture);
1 ✔
4768
            if (prior != null) {
1 ✔
4769
              return prior;
1 ✔
4770
            }
4771
          }
4772

4773
          boolean[] added = { false };
1 ✔
4774
          var hints = new LocalCache.RemapHints();
1 ✔
4775
          var computed = (CompletableFuture<V>) cache.compute(key, (K k, @Nullable V oldValue) -> {
1 ✔
4776
            var oldValueFuture = (CompletableFuture<V>) oldValue;
1 ✔
4777
            added[0] = (oldValueFuture == null)
1 ✔
4778
                || (oldValueFuture.isDone() && (Async.getIfReady(oldValueFuture) == null));
1 ✔
4779
            if (added[0]) {
1 ✔
4780
              return asyncValue;
1 ✔
4781
            }
4782
            hints.preserveEntry();
1 ✔
4783
            return oldValue;
1 ✔
4784
          }, expiry, /* recordLoad= */ false, hints);
4785

4786
          if (added[0]) {
1 ✔
4787
            return null;
1 ✔
4788
          } else {
4789
            V prior = Async.getWhenSuccessful(computed);
1 ✔
4790
            if (prior != null) {
1 ✔
4791
              return prior;
1 ✔
4792
            }
4793
          }
4794
        }
1 ✔
4795
      }
4796
      @SuppressWarnings("unchecked")
4797
      @Nullable V putAsync(K key, V value, long duration, TimeUnit unit) {
4798
        var expiry = (Expiry<K, V>) new AsyncExpiry<>(new FixedExpireAfterWrite<>(duration, unit));
1 ✔
4799
        var asyncValue = (V) CompletableFuture.completedFuture(value);
1 ✔
4800

4801
        var oldValueFuture = (CompletableFuture<V>) cache.put(
1 ✔
4802
            key, asyncValue, expiry, /* onlyIfAbsent= */ false);
4803
        return Async.getWhenSuccessful(oldValueFuture);
1 ✔
4804
      }
4805
      @Override public @Nullable V compute(K key,
4806
          BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
4807
          Duration duration) {
4808
        requireNonNull(key);
1 ✔
4809
        requireNonNull(duration);
1 ✔
4810
        requireNonNull(remappingFunction);
1 ✔
4811
        requireArgument(!duration.isNegative(), "duration cannot be negative: %s", duration);
1 ✔
4812
        var expiry = new FixedExpireAfterWrite<K, V>(
1 ✔
4813
            toNanosSaturated(duration), TimeUnit.NANOSECONDS);
1 ✔
4814

4815
        return cache.isAsync
1 ✔
4816
            ? computeAsync(key, remappingFunction, expiry)
1 ✔
4817
            : cache.compute(key, remappingFunction, expiry, /* recordLoad= */ true);
1 ✔
4818
      }
4819
      @Nullable V computeAsync(K key,
4820
          BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction,
4821
          Expiry<? super K, ? super V> expiry) {
4822
        // Keep in sync with LocalAsyncCache.AsMapView#compute(key, remappingFunction)
4823
        @SuppressWarnings("unchecked")
4824
        var delegate = (LocalCache<K, CompletableFuture<V>>) cache;
1 ✔
4825

4826
        @SuppressWarnings({"unchecked", "Varifier"})
4827
        @Nullable V[] newValue = (@Nullable V[]) new Object[1];
1 ✔
4828
        for (;;) {
4829
          Async.getWhenSuccessful(delegate.getIfPresentQuietly(key));
1 ✔
4830

4831
          var hints = new LocalCache.RemapHints();
1 ✔
4832
          CompletableFuture<V> valueFuture = delegate.compute(
1 ✔
4833
              key, (K k, @Nullable CompletableFuture<V> oldValueFuture) -> {
4834
                if ((oldValueFuture != null) && !oldValueFuture.isDone()) {
1 ✔
4835
                  hints.preserveEntry();
1 ✔
4836
                  return oldValueFuture;
1 ✔
4837
                }
4838

4839
                V oldValue = Async.getIfReady(oldValueFuture);
1 ✔
4840
                BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function =
1 ✔
4841
                    delegate.statsAware(remappingFunction, /* recordLoad= */ true);
1 ✔
4842
                newValue[0] = function.apply(key, oldValue);
1 ✔
4843
                return (newValue[0] == null) ? null
1 ✔
4844
                    : CompletableFuture.completedFuture(newValue[0]);
1 ✔
4845
              }, new AsyncExpiry<>(expiry), /* recordLoad= */ false, hints);
4846

4847
          if (newValue[0] != null) {
1 ✔
4848
            return newValue[0];
1 ✔
4849
          } else if (valueFuture == null) {
1 ✔
4850
            return null;
1 ✔
4851
          }
4852
        }
1 ✔
4853
      }
4854
      @Override public Map<K, V> oldest(int limit) {
4855
        return oldest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4856
      }
4857
      @Override public <T extends @Nullable Object> T oldest(
4858
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4859
        return cache.snapshot(cache.timerWheel(), transformer, mappingFunction);
1 ✔
4860
      }
4861
      @Override public Map<K, V> youngest(int limit) {
4862
        return youngest(new SizeLimiter<>(Math.min(limit, cache.size()), limit));
1 ✔
4863
      }
4864
      @Override public <T extends @Nullable Object> T youngest(
4865
          Function<Stream<CacheEntry<K, V>>, T> mappingFunction) {
4866
        return cache.snapshot(cache.timerWheel()::descendingIterator, transformer, mappingFunction);
1 ✔
4867
      }
4868
    }
4869

4870
    static final class FixedExpireAfterWrite<K, V> implements Expiry<K, V> {
4871
      final long duration;
4872
      final TimeUnit unit;
4873

4874
      FixedExpireAfterWrite(long duration, TimeUnit unit) {
1 ✔
4875
        this.duration = duration;
1 ✔
4876
        this.unit = unit;
1 ✔
4877
      }
1 ✔
4878
      @Override public long expireAfterCreate(K key, V value, long currentTime) {
4879
        return unit.toNanos(duration);
1 ✔
4880
      }
4881
      @Override public long expireAfterUpdate(
4882
          K key, V value, long currentTime, long currentDuration) {
4883
        return unit.toNanos(duration);
1 ✔
4884
      }
4885
      @CanIgnoreReturnValue
4886
      @Override public long expireAfterRead(
4887
          K key, V value, long currentTime, long currentDuration) {
4888
        return currentDuration;
1 ✔
4889
      }
4890
    }
4891

4892
    @SuppressWarnings("PreferJavaTimeOverload")
4893
    final class BoundedRefreshAfterWrite implements FixedRefresh<K, V> {
1 ✔
4894
      @Override public OptionalLong ageOf(K key, TimeUnit unit) {
4895
        requireNonNull(key);
1 ✔
4896
        requireNonNull(unit);
1 ✔
4897
        Object lookupKey = cache.nodeFactory.newLookupKey(key);
1 ✔
4898
        Node<K, V> node = cache.data.get(lookupKey);
1 ✔
4899
        if (node == null) {
1 ✔
4900
          return OptionalLong.empty();
1 ✔
4901
        }
4902
        long now = cache.expirationTicker().read();
1 ✔
4903
        boolean expired = cache.hasExpired(node, now);
1 ✔
4904
        V value = node.getValue();
1 ✔
4905
        if ((value == null) || expired || cache.isComputingAsync(value)) {
1 ✔
4906
          return OptionalLong.empty();
1 ✔
4907
        }
4908
        long age = toWriteTime(now) - writeTimeOf(node);
1 ✔
4909
        return (age < 0)
1 ✔
4910
            ? OptionalLong.empty()
1 ✔
4911
            : OptionalLong.of(unit.convert(age, TimeUnit.NANOSECONDS));
1 ✔
4912
      }
4913
      @Override public long getRefreshesAfter(TimeUnit unit) {
4914
        return unit.convert(cache.refreshAfterWriteNanos(), TimeUnit.NANOSECONDS);
1 ✔
4915
      }
4916
      @Override public void setRefreshesAfter(long duration, TimeUnit unit) {
4917
        requireNonNull(unit);
1 ✔
4918
        requireArgument(duration > 0, "duration must be positive: %s %s", duration, unit);
1 ✔
4919
        cache.setRefreshAfterWriteNanos(unit.toNanos(duration));
1 ✔
4920
        cache.scheduleAfterWrite();
1 ✔
4921
      }
1 ✔
4922
    }
4923
  }
4924

4925
  /* --------------- Loading Cache --------------- */
4926

4927
  static final class BoundedLocalLoadingCache<K, V>
4928
      extends BoundedLocalManualCache<K, V> implements LocalLoadingCache<K, V> {
4929
    private static final long serialVersionUID = 1;
4930

4931
    final Function<K, @Nullable V> mappingFunction;
4932
    final @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction;
4933

4934
    BoundedLocalLoadingCache(Caffeine<K, V> builder, CacheLoader<? super K, V> loader) {
4935
      super(builder, loader);
1 ✔
4936
      requireNonNull(loader);
1 ✔
4937
      mappingFunction = newMappingFunction(loader);
1 ✔
4938
      bulkMappingFunction = newBulkMappingFunction(loader);
1 ✔
4939
    }
1 ✔
4940

4941
    @Override
4942
    @SuppressWarnings({"DataFlowIssue", "NullAway"})
4943
    public AsyncCacheLoader<? super K, V> cacheLoader() {
4944
      return cache.cacheLoader;
1 ✔
4945
    }
4946

4947
    @Override
4948
    public Function<K, @Nullable V> mappingFunction() {
4949
      return mappingFunction;
1 ✔
4950
    }
4951

4952
    @Override
4953
    public @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction() {
4954
      return bulkMappingFunction;
1 ✔
4955
    }
4956

4957
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4958
      throw new InvalidObjectException("Proxy required");
1 ✔
4959
    }
4960

4961
    private Object writeReplace() {
4962
      return makeSerializationProxy(cache);
1 ✔
4963
    }
4964
  }
4965

4966
  /* --------------- Async Cache --------------- */
4967

4968
  static final class BoundedLocalAsyncCache<K, V> implements LocalAsyncCache<K, V>, Serializable {
4969
    private static final long serialVersionUID = 1;
4970

4971
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
4972

4973
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
4974
    @Nullable CacheView<K, V> cacheView;
4975
    @Nullable Policy<K, V> policy;
4976

4977
    @SuppressWarnings("unchecked")
4978
    BoundedLocalAsyncCache(Caffeine<K, V> builder) {
1 ✔
4979
      cache = (BoundedLocalCache<K, CompletableFuture<V>>) LocalCacheFactory
1 ✔
4980
          .newBoundedLocalCache(builder, /* cacheLoader= */ null, /* isAsync= */ true);
1 ✔
4981
    }
1 ✔
4982

4983
    @Override
4984
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
4985
      return cache;
1 ✔
4986
    }
4987

4988
    @Override
4989
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
4990
      var mv = mapView;
1 ✔
4991
      return (mv == null) ? (mapView = new AsyncAsMapView<>(this)) : mv;
1 ✔
4992
    }
4993

4994
    @Override
4995
    public Cache<K, V> synchronous() {
4996
      var cv = cacheView;
1 ✔
4997
      return (cv == null) ? (cacheView = new CacheView<>(this)) : cv;
1 ✔
4998
    }
4999

5000
    @Override
5001
    public Policy<K, V> policy() {
5002
      @Var var p = policy;
1 ✔
5003
      if (p == null) {
1 ✔
5004
        @SuppressWarnings("unchecked")
5005
        var castCache = (BoundedLocalCache<K, V>) cache;
1 ✔
5006
        Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1 ✔
5007
        @SuppressWarnings("unchecked")
5008
        var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1 ✔
5009
        p = new BoundedPolicy<>(castCache, castTransformer);
1 ✔
5010
        policy = p;
1 ✔
5011
      }
5012
      return p;
1 ✔
5013
    }
5014

5015
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
5016
      throw new InvalidObjectException("Proxy required");
1 ✔
5017
    }
5018

5019
    private Object writeReplace() {
5020
      return makeSerializationProxy(cache);
1 ✔
5021
    }
5022
  }
5023

5024
  /* --------------- Async Loading Cache --------------- */
5025

5026
  static final class BoundedLocalAsyncLoadingCache<K, V>
5027
      extends LocalAsyncLoadingCache<K, V> implements Serializable {
5028
    private static final long serialVersionUID = 1;
5029

5030
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
5031

5032
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
5033
    @Nullable Policy<K, V> policy;
5034

5035
    @SuppressWarnings("unchecked")
5036
    BoundedLocalAsyncLoadingCache(Caffeine<K, V> builder, AsyncCacheLoader<? super K, V> loader) {
5037
      super(loader);
1 ✔
5038
      cache = (BoundedLocalCache<K, CompletableFuture<V>>) LocalCacheFactory
1 ✔
5039
          .newBoundedLocalCache(builder, loader, /* isAsync= */ true);
1 ✔
5040
    }
1 ✔
5041

5042
    @Override
5043
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
5044
      return cache;
1 ✔
5045
    }
5046

5047
    @Override
5048
    public ConcurrentMap<K, CompletableFuture<V>> asMap() {
5049
      var mv = mapView;
1 ✔
5050
      return (mv == null) ? (mapView = new AsyncAsMapView<>(this)) : mv;
1 ✔
5051
    }
5052

5053
    @Override
5054
    public Policy<K, V> policy() {
5055
      @Var var p = policy;
1 ✔
5056
      if (p == null) {
1 ✔
5057
        @SuppressWarnings("unchecked")
5058
        var castCache = (BoundedLocalCache<K, V>) cache;
1 ✔
5059
        Function<CompletableFuture<V>, @Nullable V> transformer = Async::getIfReady;
1 ✔
5060
        @SuppressWarnings("unchecked")
5061
        var castTransformer = (Function<@Nullable V, @Nullable V>) transformer;
1 ✔
5062
        p = new BoundedPolicy<>(castCache, castTransformer);
1 ✔
5063
        policy = p;
1 ✔
5064
      }
5065
      return p;
1 ✔
5066
    }
5067

5068
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
5069
      throw new InvalidObjectException("Proxy required");
1 ✔
5070
    }
5071

5072
    private Object writeReplace() {
5073
      return makeSerializationProxy(cache);
1 ✔
5074
    }
5075
  }
5076
}
5077

5078
/** The namespace for field padding through inheritance. */
5079
@SuppressWarnings({"IdentifierName", "MultiVariableDeclaration"})
5080
final class BLCHeader {
5081

5082
  private BLCHeader() {}
5083

5084
  @SuppressWarnings("unused")
5085
  static class PadDrainStatus {
1 ✔
5086
    byte p000, p001, p002, p003, p004, p005, p006, p007;
5087
    byte p008, p009, p010, p011, p012, p013, p014, p015;
5088
    byte p016, p017, p018, p019, p020, p021, p022, p023;
5089
    byte p024, p025, p026, p027, p028, p029, p030, p031;
5090
    byte p032, p033, p034, p035, p036, p037, p038, p039;
5091
    byte p040, p041, p042, p043, p044, p045, p046, p047;
5092
    byte p048, p049, p050, p051, p052, p053, p054, p055;
5093
    byte p056, p057, p058, p059, p060, p061, p062, p063;
5094
    byte p064, p065, p066, p067, p068, p069, p070, p071;
5095
    byte p072, p073, p074, p075, p076, p077, p078, p079;
5096
    byte p080, p081, p082, p083, p084, p085, p086, p087;
5097
    byte p088, p089, p090, p091, p092, p093, p094, p095;
5098
    byte p096, p097, p098, p099, p100, p101, p102, p103;
5099
    byte p104, p105, p106, p107, p108, p109, p110, p111;
5100
    byte p112, p113, p114, p115, p116, p117, p118, p119;
5101
  }
5102

5103
  /** Enforces a memory layout to avoid false sharing by padding the drain status. */
5104
  abstract static class DrainStatusRef extends PadDrainStatus {
1 ✔
5105
    static final VarHandle DRAIN_STATUS = fieldVarHandle(MethodHandles.lookup(),
1 ✔
5106
        "drainStatus", VarHandle.class, DrainStatusRef.class, int.class);
5107

5108
    /** A drain is not taking place. */
5109
    static final int IDLE = 0;
5110
    /** A drain is required due to a pending write modification. */
5111
    static final int REQUIRED = 1;
5112
    /** A drain is in progress and will transition to idle. */
5113
    static final int PROCESSING_TO_IDLE = 2;
5114
    /** A drain is in progress and will transition to required. */
5115
    static final int PROCESSING_TO_REQUIRED = 3;
5116

5117
    /** The draining status of the buffers. */
5118
    volatile int drainStatus = IDLE;
1 ✔
5119

5120
    /**
5121
     * Returns whether maintenance work is needed.
5122
     *
5123
     * @param delayable if draining the read buffer can be delayed
5124
     */
5125
    @SuppressWarnings("StatementSwitchToExpressionSwitch")
5126
    boolean shouldDrainBuffers(boolean delayable) {
5127
      switch (drainStatusOpaque()) {
1 ✔
5128
        case IDLE:
5129
          return !delayable;
1 ✔
5130
        case REQUIRED:
5131
          return true;
1 ✔
5132
        case PROCESSING_TO_IDLE:
5133
        case PROCESSING_TO_REQUIRED:
5134
          return false;
1 ✔
5135
        default:
5136
          throw new IllegalStateException("Invalid drain status: " + drainStatus);
1 ✔
5137
      }
5138
    }
5139

5140
    int drainStatusOpaque() {
5141
      return (int) DRAIN_STATUS.getOpaque(this);
1 ✔
5142
    }
5143

5144
    int drainStatusAcquire() {
5145
      return (int) DRAIN_STATUS.getAcquire(this);
1 ✔
5146
    }
5147

5148
    void setDrainStatusOpaque(int drainStatus) {
5149
      DRAIN_STATUS.setOpaque(this, drainStatus);
1 ✔
5150
    }
1 ✔
5151

5152
    void setDrainStatusRelease(int drainStatus) {
5153
      DRAIN_STATUS.setRelease(this, drainStatus);
1 ✔
5154
    }
1 ✔
5155

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

© 2026 Coveralls, Inc