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

ben-manes / caffeine / #5707

02 Aug 2026 12:45AM UTC coverage: 0.106% (-99.9%) from 100.0%
#5707

push

github

ben-manes
fix wikibench trace reader after overly strict audit fixes

0 of 4235 branches covered (0.0%)

9 of 8528 relevant lines covered (0.11%)

0.0 hits per line

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

0.0
/caffeine/src/main/java/com/github/benmanes/caffeine/cache/LocalCache.java
1
/*
2
 * Copyright 2015 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 java.util.Map;
19
import java.util.concurrent.CompletableFuture;
20
import java.util.concurrent.ConcurrentMap;
21
import java.util.concurrent.Executor;
22
import java.util.function.BiFunction;
23
import java.util.function.Function;
24

25
import org.jspecify.annotations.NonNull;
26
import org.jspecify.annotations.Nullable;
27

28
import com.github.benmanes.caffeine.cache.stats.StatsCounter;
29
import com.google.errorprone.annotations.CanIgnoreReturnValue;
30

31
/**
32
 * An in-memory cache providing thread safety and atomicity guarantees. This interface provides an
33
 * extension to {@link ConcurrentMap} for use with skeletal implementations.
34
 *
35
 * @author ben.manes@gmail.com (Ben Manes)
36
 */
37
interface LocalCache<K, V extends @Nullable Object> extends ConcurrentMap<K, V> {
38

39
  /** Returns whether this cache is asynchronous. */
40
  boolean isAsync();
41

42
  /** Returns whether this cache has statistics enabled. */
43
  boolean isRecordingStats();
44

45
  /** Returns the {@link StatsCounter} used by this cache. */
46
  StatsCounter statsCounter();
47

48
  /** Asynchronously sends a removal notification to the listener. */
49
  void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause);
50

51
  /** Returns the removal listener, or {@code null} if none is configured. */
52
  @Nullable RemovalListener<K, V> removalListener();
53

54
  /** Returns the {@link Executor} used by this cache. */
55
  Executor executor();
56

57
  /** Returns the map of in-flight refresh operations. */
58
  ConcurrentMap<Object, CompletableFuture<?>> refreshes();
59

60
  /** Returns the {@link Expiry} used by this cache. */
61
  @Nullable Expiry<K, V> expiry();
62

63
  /** Returns the {@link Ticker} used by this cache for statistics. */
64
  Ticker statsTicker();
65

66
  /** See {@link Cache#estimatedSize()}. */
67
  long estimatedSize();
68

69
  /** Returns if the keys are weak reference garbage collected. */
70
  boolean collectKeys();
71

72
  /** Returns the reference key. */
73
  Object referenceKey(K key);
74

75
  /**
76
   * Returns whether an absent entry has expired or has been reference collected but has not yet
77
   * been removed from the cache.
78
   */
79
  boolean isPendingEviction(K key);
80

81
  /**
82
   * See {@link Cache#getIfPresent(Object)}. This method differs by accepting a parameter of whether
83
   * to record the hit-and-miss statistics based on the success of this operation.
84
   */
85
  @Nullable V getIfPresent(K key, boolean recordStats);
86

87
  /**
88
   * See {@link Cache#getIfPresent(Object)}. This method differs by not recording the access with
89
   * the statistics nor the eviction policy.
90
   */
91
  @Nullable V getIfPresentQuietly(Object key);
92

93
  /** See {@link Cache#getAllPresent}. */
94
  Map<K, V> getAllPresent(Iterable<? extends K> keys);
95

96
  @Override
97
  default boolean replace(K key, V oldValue, V newValue) {
98
    return replace(key, oldValue, newValue, /* shouldDiscardRefresh= */ true, /* quietly= */ false);
×
99
  }
100

101
  /**
102
   * See {@link ConcurrentMap#replace(Object, Object, Object)}. This method differs by optionally
103
   * not discarding an in-flight refresh for the entry if replaced and, when quiet, by not
104
   * recording the update as an access with the eviction policy.
105
   */
106
  @CanIgnoreReturnValue
107
  boolean replace(K key, V oldValue, V newValue, boolean shouldDiscardRefresh, boolean quietly);
108

109
  @Override
110
  default @Nullable V compute(K key,
111
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction) {
112
    return compute(key, remappingFunction, expiry(),
×
113
        /* recordLoad= */ true, /* recordLoadFailure= */ true);
114
  }
115

116
  /**
117
   * See {@link ConcurrentMap#compute}. This method differs by accepting parameters indicating
118
   * whether to record load statistics based on the success of this operation.
119
   */
120
  default @Nullable V compute(K key,
121
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction,
122
      @Nullable Expiry<? super K, ? super V> expiry,
123
      boolean recordLoad, boolean recordLoadFailure) {
124
    return compute(key, remappingFunction, expiry, recordLoad, recordLoadFailure,
×
125
        /* hints= */ null);
126
  }
127

128
  /**
129
   * See {@link ConcurrentMap#compute}. This method differs by accepting parameters indicating
130
   * whether to record load statistics and an optional {@link RemapHints} the remapping function
131
   * may set to signal a same-instance no-op return (e.g. a refresh that needs to be discarded
132
   * without touching the entry, or a putIfAbsent-style query that should not interfere with an
133
   * in-flight refresh). The {@code hints} is captured by the function which may mutate the fields
134
   * to communicate intent back to the cache.
135
   */
136
  @Nullable V compute(K key,
137
      BiFunction<? super K, ? super V, ? extends @Nullable V> remappingFunction,
138
      @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad,
139
      boolean recordLoadFailure, @Nullable RemapHints hints);
140

141
  @Override
142
  default @Nullable V computeIfAbsent(K key,
143
      Function<? super K, ? extends @Nullable V> mappingFunction) {
144
    return computeIfAbsent(key, mappingFunction, /* recordStats= */ true, /* recordLoad= */ true);
×
145
  }
146

147
  /**
148
   * See {@link ConcurrentMap#computeIfAbsent}. This method differs by accepting parameters
149
   * indicating how to record statistics.
150
   */
151
  @Nullable V computeIfAbsent(K key, Function<? super K, ? extends @Nullable V> mappingFunction,
152
      boolean recordStats, boolean recordLoad);
153

154
  /** See {@link Cache#invalidateAll(Iterable)}. */
155
  default void invalidateAll(Iterable<?> keys) {
156
    for (Object key : keys) {
×
157
      remove(key);
×
158
    }
×
159
  }
×
160

161
  /** See {@link Cache#cleanUp}. */
162
  void cleanUp();
163

164
  /** Notify the removal listener of a replacement if the value reference was changed. */
165
  @SuppressWarnings({"FutureReturnValueIgnored", "UnnecessaryReturnStatement"})
166
  default void notifyOnReplace(K key, @Nullable V oldValue, @NonNull V newValue) {
167
    if ((oldValue == null) || (oldValue == newValue) || (removalListener() == null)) {
×
168
      return;
×
169
    } else if (isAsync()) {
×
170
      var oldFuture = (CompletableFuture<?>) oldValue;
×
171
      var newFuture = (CompletableFuture<?>) newValue;
×
172
      newFuture.whenComplete((nv, e) -> {
×
173
        if (e == null) {
×
174
          oldFuture.thenAccept(ov -> {
×
175
            if (nv != ov) {
×
176
              notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
177
            }
178
          });
×
179
        } else {
180
          notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
181
        }
182
      });
×
183
    } else {
×
184
      notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
185
    }
186
  }
×
187

188
  /** Decorates the mapping function to record statistics if enabled, recording a miss if called. */
189
  default <T, R> Function<? super T, ? extends @Nullable R> statsAware(
190
      Function<? super T, ? extends @Nullable R> mappingFunction, boolean recordLoad) {
191
    if (!isRecordingStats()) {
×
192
      return mappingFunction;
×
193
    }
194
    return key -> {
×
195
      R value;
196
      statsCounter().recordMisses(1);
×
197
      long startTime = statsTicker().read();
×
198
      try {
199
        value = mappingFunction.apply(key);
×
200
      } catch (Throwable t) {
×
201
        statsCounter().recordLoadFailure(statsTicker().read() - startTime);
×
202
        throw t;
×
203
      }
×
204
      long loadTime = statsTicker().read() - startTime;
×
205
      if (recordLoad) {
×
206
        if (value == null) {
×
207
          statsCounter().recordLoadFailure(loadTime);
×
208
        } else {
209
          statsCounter().recordLoadSuccess(loadTime);
×
210
        }
211
      }
212
      return value;
×
213
    };
214
  }
215

216
  /** Decorates the remapping function to record statistics if enabled. */
217
  default <T, U, R> BiFunction<? super T, ? super U, ? extends @Nullable R> statsAware(
218
      BiFunction<? super T, ? super U, ? extends R> remappingFunction) {
219
    return statsAware(remappingFunction, /* recordLoad= */ true, /* recordLoadFailure= */ true);
×
220
  }
221

222
  /** Decorates the remapping function to record statistics if enabled. */
223
  default <T, U, R> BiFunction<? super T, ? super U, ? extends @Nullable R> statsAware(
224
      BiFunction<? super T, ? super U, ? extends @Nullable R> remappingFunction,
225
      boolean recordLoad, boolean recordLoadFailure) {
226
    if (!isRecordingStats()) {
×
227
      return remappingFunction;
×
228
    }
229
    return (t, u) -> {
×
230
      R result;
231
      long startTime = statsTicker().read();
×
232
      try {
233
        result = remappingFunction.apply(t, u);
×
234
      } catch (Throwable e) {
×
235
        if (recordLoadFailure) {
×
236
          statsCounter().recordLoadFailure(statsTicker().read() - startTime);
×
237
        }
238
        throw e;
×
239
      }
×
240
      long loadTime = statsTicker().read() - startTime;
×
241
      if (recordLoad) {
×
242
        if (result == null) {
×
243
          statsCounter().recordLoadFailure(loadTime);
×
244
        } else {
245
          statsCounter().recordLoadSuccess(loadTime);
×
246
        }
247
      }
248
      return result;
×
249
    };
250
  }
251

252
  /**
253
   * Mutable hints that the remapping function may set when returning the same value instance to
254
   * signal a no-op (to skip writes to the entry's metadata or leave an in-flight refresh intact).
255
   */
256
  final class RemapHints {
×
257
    /**
258
     * Skip writes to the entry's metadata (accessTime, writeTime, variableTime, and weight) for a
259
     * same-instance return. Used by callers that detect a no-op.
260
     */
261
    boolean preserveTimestamps;
262

263
    /** Additionally, leave any in-flight refresh intact so that no-op paths do not interfere. */
264
    boolean preserveRefresh;
265
  }
266
}
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