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

ben-manes / caffeine / #5848

28 Nov 2026 03:37AM UTC coverage: 99.979% (-0.01%) from 99.989%
#5848

push

github

ben-manes
restore coverage lost to recent fixes

4923 of 4934 branches covered (99.78%)

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

2 existing lines in 1 file now uncovered.

9371 of 9373 relevant lines covered (99.98%)

1.0 hits per line

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

99.92
/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 and the entry behind it has expired, so subsequent
199
   * passes can resume from the next-oldest entry. The access-order scan does not, because those
200
   * queues are also the eviction order, so a lost reorder defers reaping the entries behind its
201
   * head until that head is read again or 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 !
UNCOV
711
        break;
×
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 = (next != null)
1 ✔
970
            && ((last.getWriteTime() - node.getWriteTime()) < 0)
1 ✔
971
            && ((now - next.getWriteTime()) >= duration);
1 ✔
972
        if (stalePosition || isComputingAsync(node.getValue())) {
1 ✔
973
          writeOrderDeque().moveToBack(node);
1 ✔
974
          node = next;
1 ✔
975
          continue;
1 ✔
976
        }
977
        return;
1 ✔
978
      }
979
      evictEntry(node, RemovalCause.EXPIRED, now);
1 ✔
980
      remaining--;
1 ✔
981

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

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

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

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

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

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

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

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

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

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

1127
    synchronized (node) {
1 ✔
1128
      logIfAlive(node);
1 ✔
1129
      makeDead(node);
1 ✔
1130
    }
1 ✔
1131

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

1138
    return true;
1 ✔
1139
  }
1140

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1457
    return null;
1 ✔
1458
  }
1459

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1832
      drainKeyReferences();
1 ✔
1833
      drainValueReferences();
1 ✔
1834

1835
      long now = expirationTicker().read();
1 ✔
1836
      expireEntries(now);
1 ✔
1837
      evictEntries(now);
1 ✔
1838

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2050
        climber().recordMiss();
1 ✔
2051
      }
2052

2053
      // a removal may precede this task; make its node dead to release the weight charged above
2054
      synchronized (node) {
1 ✔
2055
        if (!node.isAlive()) {
1 ✔
2056
          makeDead(node);
1 ✔
2057
          return;
1 ✔
2058
        }
2059
      }
1 ✔
2060
      if (expiresAfterWrite()) {
1 ✔
2061
        writeOrderDeque().offerLast(node);
1 ✔
2062
      }
2063
      if (expiresVariable()) {
1 ✔
2064
        timerWheel().schedule(node);
1 ✔
2065
      }
2066
      if (evicts()) {
1 ✔
2067
        var keyRef = node.getKeyReferenceOrNull();
1 ✔
2068
        if ((keyRef != null) && node.isAlive()) {
1 ✔
2069
          frequencySketch().increment(keyRef);
1 ✔
2070
        }
2071
        if (weight > windowMaximum()) {
1 ✔
2072
          accessOrderWindowDeque().offerFirst(node);
1 ✔
2073
        } else {
2074
          accessOrderWindowDeque().offerLast(node);
1 ✔
2075
        }
2076
        if (weight > maximum()) {
1 ✔
2077
          evictEntry(node, RemovalCause.SIZE, expirationTicker().read());
1 ✔
2078
        }
2079
      } else if (expiresAfterAccess()) {
1 ✔
2080
        accessOrderWindowDeque().offerLast(node);
1 ✔
2081
      }
2082
    }
1 ✔
2083
  }
2084

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

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

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

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

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

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

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

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

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

2172
    private final boolean hit;
2173
    private final boolean miss;
2174
    private final boolean usage;
2175

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

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

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

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

2198
  /* --------------- Concurrent Map Support --------------- */
2199

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2310
    unlink(node);
1 ✔
2311

2312
    synchronized (node) {
1 ✔
2313
      logIfAlive(node);
1 ✔
2314
      makeDead(node);
1 ✔
2315
    }
1 ✔
2316

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2610
          discardRefresh(lookupKey);
1 ✔
2611
        }
2612

2613
        setVariableTime(prior, varTime);
1 ✔
2614
        setAccessTime(prior, expirationTime);
1 ✔
2615
      }
1 ✔
2616

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

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

2637
      return expired ? null : oldValue;
1 ✔
2638
    }
2639
  }
2640

2641
  @Override
2642
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
2643
  public @Nullable V remove(@Nullable Object key) {
2644
    requireNonNull(key);
1 ✔
2645

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

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

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

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

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

2732
    return (removeCause == RemovalCause.EXPLICIT);
1 ✔
2733
  }
2734

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

2756
        long varTime = expireAfterUpdate(n, key, value, expiry(), ctx.now);
1 ✔
2757
        n.setValue(value, valueReferenceQueue());
1 ✔
2758
        n.setWeight(weight);
1 ✔
2759

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

2772
    if ((node == null) || (ctx.nodeKey == null) || (ctx.oldValue == null)) {
1 ✔
2773
      if (ctx.garbage) {
1 ✔
2774
        scheduleDrainBuffers();
1 ✔
2775
      }
2776
      return null;
1 ✔
2777
    }
2778

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

2786
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, value);
1 ✔
2787
    return ctx.oldValue;
1 ✔
2788
  }
2789

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

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

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

2833
        if (shouldDiscardRefresh) {
1 ✔
2834
          discardRefresh(k);
1 ✔
2835
        }
2836
      }
1 ✔
2837
      return n;
1 ✔
2838
    });
2839

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

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

2854
    notifyOnReplace(ctx.nodeKey, ctx.oldValue, newValue);
1 ✔
2855
    return true;
1 ✔
2856
  }
2857

2858
  @Override
2859
  public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
2860
    requireNonNull(function);
1 ✔
2861

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

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

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

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

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

2939
        ctx.cause = actualCause;
1 ✔
2940
        notifyEviction(ctx.nodeKey, ctx.oldValue, actualCause);
1 ✔
2941

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

2954
          n.setValue(ctx.newValue, valueReferenceQueue());
1 ✔
2955
          n.setWeight(ctx.newWeight);
1 ✔
2956

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

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

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

3003
    return ctx.newValue;
1 ✔
3004
  }
3005

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3174
          if (ctx.newValue != ctx.oldValue) {
1 ✔
3175
            n.setValue(ctx.newValue, valueReferenceQueue());
1 ✔
3176
          }
3177
          n.setWeight(ctx.newWeight);
1 ✔
3178

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

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

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

3241
    if (ctx.exception != null) {
1 ✔
3242
      throw toUnchecked(ctx.exception);
1 ✔
3243
    }
3244
    return ctx.newValue;
1 ✔
3245
  }
3246

3247
  @Override
3248
  public void forEach(BiConsumer<? super K, ? super V> action) {
3249
    requireNonNull(action);
1 ✔
3250

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

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

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

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

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

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

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

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

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

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

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

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

3481
    evictionLock.lock();
1 ✔
3482
    try {
3483
      maintenance(/* ignored */ null);
1 ✔
3484

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

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

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

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

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

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

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

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

3598
    long now;
3599
    int oldWeight;
3600
    boolean garbage;
3601
    boolean exceedsTolerance;
3602
  }
3603

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

3614
    long now;
3615
    int oldWeight;
3616
    int newWeight;
3617
    boolean unmodified;
3618
    boolean exceedsTolerance;
3619
  }
3620

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

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

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

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

3644
    long weightedSize;
3645

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

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

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

3669
    KeySetView(BoundedLocalCache<K, V> cache) {
1 ✔
3670
      this.cache = requireNonNull(cache);
1 ✔
3671
    }
1 ✔
3672

3673
    @Override
3674
    public int size() {
3675
      return cache.size();
1 ✔
3676
    }
3677

3678
    @Override
3679
    public void clear() {
3680
      cache.clear();
1 ✔
3681
    }
1 ✔
3682

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

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

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

3720
    @Override
3721
    public boolean remove(@Nullable Object o) {
3722
      return (cache.remove(o) != null);
1 ✔
3723
    }
3724

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

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

3749
    @Override
3750
    public Iterator<K> iterator() {
3751
      return new KeyIterator<>(cache);
1 ✔
3752
    }
3753

3754
    @Override
3755
    public Spliterator<K> spliterator() {
3756
      return new KeySpliterator<>(cache);
1 ✔
3757
    }
3758
  }
3759

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

3764
    KeyIterator(BoundedLocalCache<K, V> cache) {
1 ✔
3765
      this.iterator = new EntryIterator<>(cache);
1 ✔
3766
    }
1 ✔
3767

3768
    @Override
3769
    public boolean hasNext() {
3770
      return iterator.hasNext();
1 ✔
3771
    }
3772

3773
    @Override
3774
    public K next() {
3775
      return iterator.nextKey();
1 ✔
3776
    }
3777

3778
    @Override
3779
    public void remove() {
3780
      iterator.remove();
1 ✔
3781
    }
1 ✔
3782
  }
3783

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

3789
    KeySpliterator(BoundedLocalCache<K, V> cache) {
3790
      this(cache, cache.data.values().spliterator());
1 ✔
3791
    }
1 ✔
3792

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

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

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

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

3845
    @Override
3846
    public long estimateSize() {
3847
      return spliterator.estimateSize();
1 ✔
3848
    }
3849

3850
    @Override
3851
    public int characteristics() {
3852
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
3853
    }
3854
  }
3855

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

3860
    ValuesView(BoundedLocalCache<K, V> cache) {
1 ✔
3861
      this.cache = requireNonNull(cache);
1 ✔
3862
    }
1 ✔
3863

3864
    @Override
3865
    public int size() {
3866
      return cache.size();
1 ✔
3867
    }
3868

3869
    @Override
3870
    public void clear() {
3871
      cache.clear();
1 ✔
3872
    }
1 ✔
3873

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

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

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

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

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

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

3955
    @Override
3956
    public Iterator<V> iterator() {
3957
      return new ValueIterator<>(cache);
1 ✔
3958
    }
3959

3960
    @Override
3961
    public Spliterator<V> spliterator() {
3962
      return new ValueSpliterator<>(cache);
1 ✔
3963
    }
3964
  }
3965

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

3970
    ValueIterator(BoundedLocalCache<K, V> cache) {
1 ✔
3971
      this.iterator = new EntryIterator<>(cache);
1 ✔
3972
    }
1 ✔
3973

3974
    @Override
3975
    public boolean hasNext() {
3976
      return iterator.hasNext();
1 ✔
3977
    }
3978

3979
    @Override
3980
    public V next() {
3981
      return iterator.nextValue();
1 ✔
3982
    }
3983

3984
    @Override
3985
    public void remove() {
3986
      iterator.remove();
1 ✔
3987
    }
1 ✔
3988
  }
3989

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

3995
    ValueSpliterator(BoundedLocalCache<K, V> cache) {
3996
      this(cache, cache.data.values().spliterator());
1 ✔
3997
    }
1 ✔
3998

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

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

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

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

4051
    @Override
4052
    public long estimateSize() {
4053
      return spliterator.estimateSize();
1 ✔
4054
    }
4055

4056
    @Override
4057
    public int characteristics() {
4058
      return CONCURRENT | NONNULL;
1 ✔
4059
    }
4060
  }
4061

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

4066
    EntrySetView(BoundedLocalCache<K, V> cache) {
1 ✔
4067
      this.cache = requireNonNull(cache);
1 ✔
4068
    }
1 ✔
4069

4070
    @Override
4071
    public int size() {
4072
      return cache.size();
1 ✔
4073
    }
4074

4075
    @Override
4076
    public void clear() {
4077
      cache.clear();
1 ✔
4078
    }
1 ✔
4079

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

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

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

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

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

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

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

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

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

4187
    @Nullable K key;
4188
    @Nullable V value;
4189
    @Nullable K removalKey;
4190
    @Nullable Node<K, V> next;
4191

4192
    EntryIterator(BoundedLocalCache<K, V> cache) {
1 ✔
4193
      this.iterator = cache.data.values().iterator();
1 ✔
4194
      this.cache = cache;
1 ✔
4195
    }
1 ✔
4196

4197
    @Override
4198
    public boolean hasNext() {
4199
      if (next != null) {
1 ✔
4200
        return true;
1 ✔
4201
      }
4202

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

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

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

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

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

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

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

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

4277
    EntrySpliterator(BoundedLocalCache<K, V> cache) {
4278
      this(cache, cache.data.values().spliterator());
1 ✔
4279
    }
1 ✔
4280

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

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

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

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

4333
    @Override
4334
    public long estimateSize() {
4335
      return spliterator.estimateSize();
1 ✔
4336
    }
4337

4338
    @Override
4339
    public int characteristics() {
4340
      return DISTINCT | CONCURRENT | NONNULL;
1 ✔
4341
    }
4342
  }
4343

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

4348
    PerformCleanupTask(BoundedLocalCache<?, ?> cache) {
4349
      super(cache);
1 ✔
4350
    }
1 ✔
4351

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

4370
  /* --------------- Manual Cache --------------- */
4371

4372
  static class BoundedLocalManualCache<K, V> implements LocalManualCache<K, V>, Serializable {
4373
    private static final long serialVersionUID = 1;
4374

4375
    final BoundedLocalCache<K, V> cache;
4376

4377
    @Nullable Policy<K, V> policy;
4378

4379
    BoundedLocalManualCache(Caffeine<K, V> builder) {
4380
      this(builder, null);
1 ✔
4381
    }
1 ✔
4382

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

4387
    @Override
4388
    public final BoundedLocalCache<K, V> cache() {
4389
      return cache;
1 ✔
4390
    }
4391

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

4403
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4404
      throw new InvalidObjectException("Proxy required");
1 ✔
4405
    }
4406

4407
    private Object writeReplace() {
4408
      return makeSerializationProxy(cache);
1 ✔
4409
    }
4410
  }
4411

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

4418
    @Nullable Optional<Eviction<K, V>> eviction;
4419
    @Nullable Optional<FixedRefresh<K, V>> refreshes;
4420
    @Nullable Optional<FixedExpiration<K, V>> afterWrite;
4421
    @Nullable Optional<FixedExpiration<K, V>> afterAccess;
4422
    @Nullable Optional<VarExpiration<K, V>> variable;
4423

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

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

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

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

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

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

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

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

4770
            V prior = Async.getWhenSuccessful(priorFuture);
1 ✔
4771
            if (prior != null) {
1 ✔
4772
              return prior;
1 ✔
4773
            }
4774
          }
4775

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

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

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

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

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

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

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

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

4873
    static final class FixedExpireAfterWrite<K, V> implements Expiry<K, V> {
4874
      final long duration;
4875
      final TimeUnit unit;
4876

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

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

4928
  /* --------------- Loading Cache --------------- */
4929

4930
  static final class BoundedLocalLoadingCache<K, V>
4931
      extends BoundedLocalManualCache<K, V> implements LocalLoadingCache<K, V> {
4932
    private static final long serialVersionUID = 1;
4933

4934
    final Function<K, @Nullable V> mappingFunction;
4935
    final @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction;
4936

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

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

4950
    @Override
4951
    public Function<K, @Nullable V> mappingFunction() {
4952
      return mappingFunction;
1 ✔
4953
    }
4954

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

4960
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
4961
      throw new InvalidObjectException("Proxy required");
1 ✔
4962
    }
4963

4964
    private Object writeReplace() {
4965
      return makeSerializationProxy(cache);
1 ✔
4966
    }
4967
  }
4968

4969
  /* --------------- Async Cache --------------- */
4970

4971
  static final class BoundedLocalAsyncCache<K, V> implements LocalAsyncCache<K, V>, Serializable {
4972
    private static final long serialVersionUID = 1;
4973

4974
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
4975

4976
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
4977
    @Nullable CacheView<K, V> cacheView;
4978
    @Nullable Policy<K, V> policy;
4979

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

4986
    @Override
4987
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
4988
      return cache;
1 ✔
4989
    }
4990

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

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

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

5018
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
5019
      throw new InvalidObjectException("Proxy required");
1 ✔
5020
    }
5021

5022
    private Object writeReplace() {
5023
      return makeSerializationProxy(cache);
1 ✔
5024
    }
5025
  }
5026

5027
  /* --------------- Async Loading Cache --------------- */
5028

5029
  static final class BoundedLocalAsyncLoadingCache<K, V>
5030
      extends LocalAsyncLoadingCache<K, V> implements Serializable {
5031
    private static final long serialVersionUID = 1;
5032

5033
    final BoundedLocalCache<K, CompletableFuture<V>> cache;
5034

5035
    @Nullable ConcurrentMap<K, CompletableFuture<V>> mapView;
5036
    @Nullable Policy<K, V> policy;
5037

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

5045
    @Override
5046
    public BoundedLocalCache<K, CompletableFuture<V>> cache() {
5047
      return cache;
1 ✔
5048
    }
5049

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

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

5071
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
5072
      throw new InvalidObjectException("Proxy required");
1 ✔
5073
    }
5074

5075
    private Object writeReplace() {
5076
      return makeSerializationProxy(cache);
1 ✔
5077
    }
5078
  }
5079
}
5080

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

5085
  private BLCHeader() {}
5086

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

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

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

5120
    /** The draining status of the buffers. */
5121
    volatile int drainStatus = IDLE;
1 ✔
5122

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

5143
    int drainStatusOpaque() {
5144
      return (int) DRAIN_STATUS.getOpaque(this);
1 ✔
5145
    }
5146

5147
    int drainStatusAcquire() {
5148
      return (int) DRAIN_STATUS.getAcquire(this);
1 ✔
5149
    }
5150

5151
    void setDrainStatusOpaque(int drainStatus) {
5152
      DRAIN_STATUS.setOpaque(this, drainStatus);
1 ✔
5153
    }
1 ✔
5154

5155
    void setDrainStatusRelease(int drainStatus) {
5156
      DRAIN_STATUS.setRelease(this, drainStatus);
1 ✔
5157
    }
1 ✔
5158

5159
    boolean casDrainStatus(int expect, int update) {
5160
      return DRAIN_STATUS.compareAndSet(this, expect, update);
1 ✔
5161
    }
5162
  }
5163
}
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