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

ben-manes / caffeine / #5846

28 Nov 2026 12:38AM UTC coverage: 99.797% (-0.2%) from 99.979%
#5846

push

github

ben-manes
dependency updates

4908 of 4930 branches covered (99.55%)

9352 of 9371 relevant lines covered (99.8%)

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 ✔
711
        break;
1 ✔
712
      }
713
      if (remaining == 0) {
1 ✔
714
        // A resize can leave the window arbitrarily oversized, so the transfer is bounded per
715
        // maintenance cycle and re-armed to drain the backlog across cycles
716
        setDrainStatusOpaque(PROCESSING_TO_REQUIRED);
1 ✔
717
        break;
1 ✔
718
      }
719

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

732
    return first;
1 ✔
733
  }
734

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1137
    return true;
1 ✔
1138
  }
1139

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1456
    return null;
1 ✔
1457
  }
1458

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2197
  /* --------------- Concurrent Map Support --------------- */
2198

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2309
    unlink(node);
1 ✔
2310

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2609
          discardRefresh(lookupKey);
1 ✔
2610
        }
2611

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3002
    return ctx.newValue;
1 ✔
3003
  }
3004

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3643
    long weightedSize;
3644

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4369
  /* --------------- Manual Cache --------------- */
4370

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

4374
    final BoundedLocalCache<K, V> cache;
4375

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4927
  /* --------------- Loading Cache --------------- */
4928

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

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

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

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

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

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

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

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

4968
  /* --------------- Async Cache --------------- */
4969

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

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

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

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

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

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

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

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

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

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

5026
  /* --------------- Async Loading Cache --------------- */
5027

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

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

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

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

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

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

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

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

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

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

5084
  private BLCHeader() {}
5085

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

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

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

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

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

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

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

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

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

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