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

ben-manes / caffeine / #5155

03 Dec 2025 02:00AM UTC coverage: 0.0% (-100.0%) from 100.0%
#5155

push

github

ben-manes
add loading type to parameterized test dimensions to reduce task size

0 of 3834 branches covered (0.0%)

0 of 7848 relevant lines covered (0.0%)

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.Nullable;
26

27
import com.github.benmanes.caffeine.cache.stats.StatsCounter;
28

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

37
  /** Returns whether this cache is asynchronous. */
38
  boolean isAsync();
39

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

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

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

49
  /** Returns the {@link Executor} used by this cache. */
50
  Executor executor();
51

52
  /** Returns the map of in-flight refresh operations. */
53
  ConcurrentMap<Object, CompletableFuture<?>> refreshes();
54

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

58
  /** Returns the {@link Ticker} used by this cache for statistics. */
59
  Ticker statsTicker();
60

61
  /** See {@link Cache#estimatedSize()}. */
62
  long estimatedSize();
63

64
  /** Returns the reference key. */
65
  Object referenceKey(K key);
66

67
  /**
68
   * Returns whether an absent entry has expired or has been reference collected but has not yet
69
   * been removed from the cache.
70
   */
71
  boolean isPendingEviction(K key);
72

73
  /**
74
   * See {@link Cache#getIfPresent(K)}. This method differs by accepting a parameter of whether
75
   * to record the hit-and-miss statistics based on the success of this operation.
76
   */
77
  @Nullable
78
  V getIfPresent(K key, boolean recordStats);
79

80
  /**
81
   * See {@link Cache#getIfPresent(K)}. This method differs by not recording the access with
82
   * the statistics nor the eviction policy.
83
   */
84
  @Nullable
85
  V getIfPresentQuietly(Object key);
86

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

90
  /**
91
   * See {@link ConcurrentMap#replace(K, K, V)}. This method differs by optionally not discarding an
92
   * in-flight refresh for the entry if replaced.
93
   */
94
  boolean replace(K key, V oldValue, V newValue, boolean shouldDiscardRefresh);
95

96
  @Override
97
  default @Nullable V compute(K key,
98
      BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
99
    return compute(key, remappingFunction, expiry(),
×
100
        /* recordLoad= */ true, /* recordLoadFailure= */ true);
101
  }
102

103
  /**
104
   * See {@link ConcurrentMap#compute}. This method differs by accepting parameters indicating
105
   * whether to record load statistics based on the success of this operation.
106
   */
107
  @Nullable V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction,
108
      @Nullable Expiry<? super K, ? super V> expiry, boolean recordLoad, boolean recordLoadFailure);
109

110
  @Override
111
  default @Nullable V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
112
    return computeIfAbsent(key, mappingFunction, /* recordStats= */ true, /* recordLoad= */ true);
×
113
  }
114

115
  /**
116
   * See {@link ConcurrentMap#computeIfAbsent}. This method differs by accepting parameters
117
   * indicating how to record statistics.
118
   */
119
  @Nullable V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction,
120
      boolean recordStats, boolean recordLoad);
121

122
  /** See {@link Cache#invalidateAll(Iterable)}. */
123
  default void invalidateAll(Iterable<?> keys) {
124
    for (Object key : keys) {
×
125
      remove(key);
×
126
    }
×
127
  }
×
128

129
  /** See {@link Cache#cleanUp}. */
130
  void cleanUp();
131

132
  /** Notify the removal listener of a replacement if the value reference was changed. */
133
  @SuppressWarnings("FutureReturnValueIgnored")
134
  default void notifyOnReplace(K key, @Nullable V oldValue, V newValue) {
135
    if ((oldValue == null) || (oldValue == newValue)) {
×
136
      return;
×
137
    } else if (isAsync()) {
×
138
      var oldFuture = (CompletableFuture<?>) oldValue;
×
139
      var newFuture = (CompletableFuture<?>) newValue;
×
140
      newFuture.whenCompleteAsync((nv, e) -> {
×
141
        if (e == null) {
×
142
          oldFuture.thenAcceptAsync(ov -> {
×
143
            if (nv != ov) {
×
144
              notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
145
            }
146
          }, executor());
×
147
        } else {
148
          notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
149
        }
150
      }, executor());
×
151
    } else {
×
152
      notifyRemoval(key, oldValue, RemovalCause.REPLACED);
×
153
    }
154
  }
×
155

156
  /** Decorates the mapping function to record statistics if enabled, recording a miss if called. */
157
  default <T, R> Function<? super T, ? extends R> statsAware(
158
      Function<? super T, ? extends R> mappingFunction, boolean recordLoad) {
159
    if (!isRecordingStats()) {
×
160
      return mappingFunction;
×
161
    }
162
    return key -> {
×
163
      R value;
164
      statsCounter().recordMisses(1);
×
165
      long startTime = statsTicker().read();
×
166
      try {
167
        value = mappingFunction.apply(key);
×
168
      } catch (Throwable t) {
×
169
        statsCounter().recordLoadFailure(statsTicker().read() - startTime);
×
170
        throw t;
×
171
      }
×
172
      long loadTime = statsTicker().read() - startTime;
×
173
      if (recordLoad) {
×
174
        if (value == null) {
×
175
          statsCounter().recordLoadFailure(loadTime);
×
176
        } else {
177
          statsCounter().recordLoadSuccess(loadTime);
×
178
        }
179
      }
180
      return value;
×
181
    };
182
  }
183

184
  /** Decorates the remapping function to record statistics if enabled. */
185
  default <T, U, R> BiFunction<? super T, ? super U, ? extends R> statsAware(
186
      BiFunction<? super T, ? super U, ? extends R> remappingFunction) {
187
    return statsAware(remappingFunction, /* recordLoad= */ true, /* recordLoadFailure= */ true);
×
188
  }
189

190
  /** Decorates the remapping function to record statistics if enabled. */
191
  default <T, U, R> BiFunction<? super T, ? super U, ? extends R> statsAware(
192
      BiFunction<? super T, ? super U, ? extends R> remappingFunction,
193
      boolean recordLoad, boolean recordLoadFailure) {
194
    if (!isRecordingStats()) {
×
195
      return remappingFunction;
×
196
    }
197
    return (t, u) -> {
×
198
      R result;
199
      long startTime = statsTicker().read();
×
200
      try {
201
        result = remappingFunction.apply(t, u);
×
202
      } catch (RuntimeException | Error e) {
×
203
        if (recordLoadFailure) {
×
204
          statsCounter().recordLoadFailure(statsTicker().read() - startTime);
×
205
        }
206
        throw e;
×
207
      }
×
208
      long loadTime = statsTicker().read() - startTime;
×
209
      if (recordLoad) {
×
210
        if (result == null) {
×
211
          statsCounter().recordLoadFailure(loadTime);
×
212
        } else {
213
          statsCounter().recordLoadSuccess(loadTime);
×
214
        }
215
      }
216
      return result;
×
217
    };
218
  }
219
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc