• 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/LocalLoadingCache.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 static com.github.benmanes.caffeine.cache.Caffeine.calculateHashMapCapacity;
19
import static com.github.benmanes.caffeine.cache.Caffeine.hasMethodOverride;
20
import static com.github.benmanes.caffeine.cache.LocalAsyncCache.composeResult;
21
import static java.util.Objects.requireNonNull;
22

23
import java.lang.System.Logger;
24
import java.lang.System.Logger.Level;
25
import java.util.Collections;
26
import java.util.LinkedHashMap;
27
import java.util.Map;
28
import java.util.Set;
29
import java.util.concurrent.CancellationException;
30
import java.util.concurrent.CompletableFuture;
31
import java.util.concurrent.CompletionException;
32
import java.util.concurrent.TimeoutException;
33
import java.util.function.Function;
34

35
import org.jspecify.annotations.Nullable;
36

37
import com.google.errorprone.annotations.Var;
38

39
/**
40
 * This class provides a skeletal implementation of the {@link LoadingCache} interface to minimize
41
 * the effort required to implement a {@link LocalCache}.
42
 *
43
 * @author ben.manes@gmail.com (Ben Manes)
44
 */
45
interface LocalLoadingCache<K, V> extends LocalManualCache<K, V>, LoadingCache<K, V> {
46
  Logger logger = System.getLogger(LocalLoadingCache.class.getName());
×
47

48
  /** Returns the {@link AsyncCacheLoader} used by this cache. */
49
  AsyncCacheLoader<? super K, V> cacheLoader();
50

51
  /** Returns the {@link CacheLoader#load} as a mapping function. */
52
  Function<K, @Nullable V> mappingFunction();
53

54
  /** Returns the {@link CacheLoader#loadAll} as a mapping function, if implemented. */
55
  @Nullable Function<Set<? extends K>, Map<K, V>> bulkMappingFunction();
56

57
  @Override
58
  @SuppressWarnings("NullAway")
59
  default V get(K key) {
60
    return cache().computeIfAbsent(key, mappingFunction());
×
61
  }
62

63
  @Override
64
  default Map<K, V> getAll(Iterable<? extends K> keys) {
65
    Function<Set<? extends K>, Map<K, V>> mappingFunction = bulkMappingFunction();
×
66
    return (mappingFunction == null)
×
67
        ? loadSequentially(keys)
×
68
        : getAll(keys, mappingFunction);
×
69
  }
70

71
  /** Sequentially loads each missing entry. */
72
  default Map<K, V> loadSequentially(Iterable<? extends K> keys) {
73
    var result = new LinkedHashMap<K, @Nullable V>(calculateHashMapCapacity(keys));
×
74
    for (K key : keys) {
×
75
      result.put(requireNonNull(key), null);
×
76
    }
×
77

78
    @Var int count = 0;
×
79
    int size = result.size();
×
80
    try {
81
      for (var iter = result.entrySet().iterator(); iter.hasNext();) {
×
82
        Map.Entry<K, @Nullable V> entry = iter.next();
×
83
        count++;
×
84

85
        V value = get(entry.getKey());
×
86
        if (value == null) {
×
87
          iter.remove();
×
88
        } else {
89
          entry.setValue(value);
×
90
        }
91
      }
×
92
    } catch (Throwable t) {
×
93
      cache().statsCounter().recordMisses(size - count);
×
94
      throw t;
×
95
    }
×
96
    @SuppressWarnings("NullableProblems")
97
    Map<K, V> unmodifiable = Collections.unmodifiableMap(result);
×
98
    return unmodifiable;
×
99
  }
100

101
  @Override
102
  @SuppressWarnings("FutureReturnValueIgnored")
103
  default CompletableFuture<V> refresh(K key) {
104
    requireNonNull(key);
×
105

106
    var startTime = new long[1];
×
107
    @SuppressWarnings({"unchecked", "Varifier"})
108
    @Nullable V[] oldValue = (V[]) new Object[1];
×
109
    @SuppressWarnings({"rawtypes", "unchecked"})
110
    @Nullable CompletableFuture<? extends V>[] reloading = new CompletableFuture[1];
×
111
    Object keyReference = cache().referenceKey(key);
×
112

113
    var future = cache().refreshes().compute(keyReference, (k, existing) -> {
×
114
      if ((existing != null) && !Async.isReady(existing) && !cache().isPendingEviction(key)) {
×
115
        return existing;
×
116
      }
117

118
      try {
119
        startTime[0] = cache().statsTicker().read();
×
120
        oldValue[0] = cache().getIfPresentQuietly(key);
×
121
        var refreshFuture = (oldValue[0] == null)
×
122
            ? cacheLoader().asyncLoad(key, cache().executor())
×
123
            : cacheLoader().asyncReload(key, oldValue[0], cache().executor());
×
124
        reloading[0] = requireNonNull(refreshFuture, "Null future");
×
125
        return refreshFuture;
×
126
      } catch (RuntimeException e) {
×
127
        throw e;
×
128
      } catch (InterruptedException e) {
×
129
        Thread.currentThread().interrupt();
×
130
        throw new CompletionException(e);
×
131
      } catch (Exception e) {
×
132
        throw new CompletionException(e);
×
133
      }
134
    });
135

136
    if (reloading[0] != null) {
×
137
      reloading[0].whenComplete((newValue, error) -> {
×
138
        long loadTime = cache().statsTicker().read() - startTime[0];
×
139
        if (error != null) {
×
140
          if (!(error instanceof CancellationException) && !(error instanceof TimeoutException)) {
×
141
            logger.log(Level.WARNING, "Exception thrown during refresh", error);
×
142
          }
143
          cache().refreshes().remove(keyReference, reloading[0]);
×
144
          cache().statsCounter().recordLoadFailure(loadTime);
×
145
          return;
×
146
        }
147

148
        try {
149
          var discard = new boolean[1];
×
150
          var hints = new LocalCache.RemapHints();
×
151
          @Nullable V value = cache().compute(key, (K k, @Nullable V currentValue) -> {
×
152
            // Keep the refresh registered until the write clears it to avoid refreshAfterWrite
153
            // readers from prematurely scheduling another reload
154
            boolean owned = (cache().refreshes().get(keyReference) == reloading[0]);
×
155
            if (owned && (currentValue == oldValue[0])) {
×
156
              return (currentValue == null) && (newValue == null) ? null : newValue;
×
157
            }
158
            // When a successor refresh owns the registration, leave it intact so a stale
159
            // completion's by-key discard cannot steal the successor's token (its fresh value
160
            // would then be discarded in turn)
161
            hints.preserveRefresh = !owned;
×
162
            hints.preserveTimestamps = true;
×
163
            discard[0] = (currentValue != newValue);
×
164
            return currentValue;
×
165
          }, cache().expiry(), /* recordLoad= */ false,
×
166
              /* recordLoadFailure= */ true, hints);
167

168
          if (discard[0] && (newValue != null)) {
×
169
            var cause = (value == null) ? RemovalCause.EXPLICIT : RemovalCause.REPLACED;
×
170
            cache().notifyRemoval(key, newValue, cause);
×
171
          }
172
          if (newValue == null) {
×
173
            cache().statsCounter().recordLoadFailure(loadTime);
×
174
          } else {
175
            cache().statsCounter().recordLoadSuccess(loadTime);
×
176
          }
177
        } catch (Throwable t) {
×
178
          logger.log(Level.WARNING, "Exception thrown during refresh", t);
×
179
          cache().statsCounter().recordLoadFailure(loadTime);
×
180
        }
×
181
      });
×
182
    }
183

184
    @SuppressWarnings("unchecked")
185
    var castedFuture = (CompletableFuture<V>) future;
×
186
    return castedFuture;
×
187
  }
188

189
  @Override
190
  default CompletableFuture<Map<K, V>> refreshAll(Iterable<? extends K> keys) {
191
    var result = new LinkedHashMap<K, CompletableFuture<@Nullable V>>(
×
192
        calculateHashMapCapacity(keys));
×
193
    for (K key : keys) {
×
194
      result.computeIfAbsent(key, this::refresh);
×
195
    }
×
196
    return composeResult(result);
×
197
  }
198

199
  /** Returns a mapping function that adapts to {@link CacheLoader#load}. */
200
  static <K, V> Function<K, @Nullable V> newMappingFunction(CacheLoader<? super K, V> cacheLoader) {
201
    return key -> {
×
202
      try {
203
        return cacheLoader.load(key);
×
204
      } catch (RuntimeException e) {
×
205
        throw e;
×
206
      } catch (InterruptedException e) {
×
207
        Thread.currentThread().interrupt();
×
208
        throw new CompletionException(e);
×
209
      } catch (Exception e) {
×
210
        throw new CompletionException(e);
×
211
      }
212
    };
213
  }
214

215
  /** Returns a mapping function that adapts to {@link CacheLoader#loadAll}, if implemented. */
216
  static <K, V> @Nullable Function<Set<? extends K>, Map<K, V>> newBulkMappingFunction(
217
      CacheLoader<? super K, V> cacheLoader) {
218
    if (!hasLoadAll(cacheLoader)) {
×
219
      return null;
×
220
    }
221
    return keysToLoad -> {
×
222
      try {
223
        @SuppressWarnings("unchecked")
224
        var loaded = (Map<K, V>) cacheLoader.loadAll(keysToLoad);
×
225
        return loaded;
×
226
      } catch (RuntimeException e) {
×
227
        throw e;
×
228
      } catch (InterruptedException e) {
×
229
        Thread.currentThread().interrupt();
×
230
        throw new CompletionException(e);
×
231
      } catch (Exception e) {
×
232
        throw new CompletionException(e);
×
233
      }
234
    };
235
  }
236

237
  /** Returns whether the supplied cache loader has bulk load functionality. */
238
  static boolean hasLoadAll(CacheLoader<?, ?> cacheLoader) {
239
    return hasMethodOverride(CacheLoader.class, cacheLoader, "loadAll", Set.class);
×
240
  }
241
}
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