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

ben-manes / caffeine / #5173

29 Dec 2025 05:27AM UTC coverage: 0.0% (-100.0%) from 100.0%
#5173

push

github

ben-manes
speed up development ci build

0 of 3838 branches covered (0.0%)

0 of 7869 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/AsyncCacheLoader.java
1
/*
2
 * Copyright 2016 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 java.util.Objects.requireNonNull;
19

20
import java.util.Map;
21
import java.util.Set;
22
import java.util.concurrent.CompletableFuture;
23
import java.util.concurrent.Executor;
24
import java.util.function.BiFunction;
25
import java.util.function.Function;
26

27
import org.jspecify.annotations.NonNull;
28
import org.jspecify.annotations.NullMarked;
29
import org.jspecify.annotations.Nullable;
30

31
/**
32
 * Computes or retrieves values asynchronously based on a key, for use in populating a
33
 * {@link AsyncLoadingCache}.
34
 * <p>
35
 * Most implementations will only need to implement {@link #asyncLoad}. Other methods may be
36
 * overridden as desired.
37
 * <p>
38
 * Usage example:
39
 * {@snippet class=com.github.benmanes.caffeine.cache.Snippets region=asyncLoader_basic lang=java}
40
 *
41
 * @param <K> the type of keys
42
 * @param <V> the type of values. A loader may return null values if and only if it declares a
43
 *     nullable value type. A cache may return null values if and only if its loader does. (Null
44
 *     values are still never <i>stored</i> in the cache.)
45
 * @author ben.manes@gmail.com (Ben Manes)
46
 */
47
@NullMarked
48
@FunctionalInterface
49
@SuppressWarnings({"JavadocDeclaration", "JavadocReference", "PMD.SignatureDeclareThrowsException"})
50
public interface AsyncCacheLoader<K, V extends @Nullable Object> {
51

52
  /**
53
   * Asynchronously computes or retrieves the value corresponding to {@code key}.
54
   * <p>
55
   * <b>Warning:</b> loading <b>must not</b> attempt to update any mappings of this cache directly.
56
   *
57
   * @param key the non-null key whose value should be loaded
58
   * @param executor the executor with which the entry may be asynchronously loaded
59
   * @return the future value associated with {@code key}
60
   * @throws Exception or Error, in which case the mapping is unchanged
61
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
62
   *         treated like any other {@code Exception} in all respects except that, when it is
63
   *         caught, the thread's interrupt status is set
64
   */
65
  CompletableFuture<? extends V> asyncLoad(K key, Executor executor) throws Exception;
66

67
  /**
68
   * Asynchronously computes or retrieves the values corresponding to {@code keys}. This method is
69
   * called by {@link AsyncLoadingCache#getAll}.
70
   * <p>
71
   * If the returned map doesn't contain all requested {@code keys}, then the entries it does
72
   * contain will be cached, and {@code getAll} will return the partial results. If the returned map
73
   * contains extra keys not present in {@code keys}, then all returned entries will be cached, but
74
   * only the entries for {@code keys} will be returned from {@code getAll}.
75
   * <p>
76
   * This method should be overridden when bulk retrieval is significantly more efficient than many
77
   * individual lookups. Note that {@link AsyncLoadingCache#getAll} will defer to individual calls
78
   * to {@link AsyncLoadingCache#get} if this method is not overridden.
79
   * <p>
80
   * <b>Warning:</b> loading <b>must not</b> attempt to update any mappings of this cache directly.
81
   *
82
   * @param keys the unique, non-null keys whose values should be loaded
83
   * @param executor the executor with which the entry may be asynchronously loaded
84
   * @return a future containing the map from each key in {@code keys} to the value associated with
85
   *         that key; <b>may not contain null values</b>
86
   * @throws Exception or Error, in which case the mappings are unchanged
87
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
88
   *         treated like any other {@code Exception} in all respects except that, when it is
89
   *         caught, the thread's interrupt status is set
90
   */
91
  default CompletableFuture<? extends Map<? extends K, ? extends @NonNull V>> asyncLoadAll(
92
      Set<? extends K> keys, Executor executor) throws Exception {
93
    throw new UnsupportedOperationException();
×
94
  }
95

96
  /**
97
   * Asynchronously computes or retrieves a replacement value corresponding to an already-cached
98
   * {@code key}. If the replacement value is not found, then the mapping will be removed if
99
   * {@code null} is computed. This method is called when an existing cache entry is refreshed by
100
   * {@link Caffeine#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
101
   * <p>
102
   * <b>Warning:</b> loading <b>must not</b> attempt to update any mappings of this cache directly
103
   * or block waiting for other cache operations to complete.
104
   * <p>
105
   * <b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
106
   *
107
   * @param key the non-null key whose value should be loaded
108
   * @param oldValue the non-null old value corresponding to {@code key}
109
   * @param executor the executor with which the entry may be asynchronously loaded
110
   * @return a future containing the new value associated with {@code key}, or containing
111
   *         {@code null} if the mapping is to be removed
112
   * @throws Exception or Error, in which case the mapping is unchanged
113
   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
114
   *         treated like any other {@code Exception} in all respects except that, when it is
115
   *         caught, the thread's interrupt status is set
116
   */
117
  default CompletableFuture<? extends V> asyncReload(
118
      K key, @NonNull V oldValue, Executor executor) throws Exception {
119
    return asyncLoad(key, executor);
×
120
  }
121

122
  /**
123
   * Returns an asynchronous cache loader that delegates to the supplied mapping function for
124
   * retrieving the values. Note that {@link #asyncLoad} will discard any additional mappings
125
   * loaded when retrieving the {@code key} prior to returning the value to the cache.
126
   * <p>
127
   * Usage example:
128
   * {@snippet class=com.github.benmanes.caffeine.cache.Snippets
129
   *           region=asyncLoader_bulk_sync lang=java}
130
   *
131
   * @param <K> the key type
132
   * @param <V> the value type
133
   * @param mappingFunction the function to asynchronously compute the values
134
   * @return an asynchronous cache loader that delegates to the supplied {@code mappingFunction}
135
   * @throws NullPointerException if the mappingFunction is null
136
   */
137
  static <K, V extends @Nullable Object> AsyncCacheLoader<K, V> bulk(
138
      Function<? super Set<? extends K>, ? extends Map<? extends K, ? extends @NonNull V>>
139
          mappingFunction) {
140
    return CacheLoader.bulk(mappingFunction);
×
141
  }
142

143
  /**
144
   * Returns an asynchronous cache loader that delegates to the supplied mapping function for
145
   * retrieving the values. Note that {@link #asyncLoad} will silently discard any additional
146
   * mappings loaded when retrieving the {@code key} prior to returning the value to the cache.
147
   * <p>
148
   * Usage example:
149
   * {@snippet class=com.github.benmanes.caffeine.cache.Snippets
150
   *           region=asyncLoader_bulk_async lang=java}
151
   *
152
   * @param <K> the key type
153
   * @param <V> the value type
154
   * @param mappingFunction the function to asynchronously compute the values
155
   * @return an asynchronous cache loader that delegates to the supplied {@code mappingFunction}
156
   * @throws NullPointerException if the mappingFunction is null
157
   */
158
  static <K, V extends @Nullable Object> AsyncCacheLoader<K, V> bulk(
159
      BiFunction<
160
          ? super Set<? extends K>,
161
          ? super Executor,
162
          ? extends CompletableFuture<? extends Map<? extends K, ? extends @NonNull V>>>
163
      mappingFunction) {
164
    requireNonNull(mappingFunction);
×
165
    return new AsyncCacheLoader<>() {
×
166
      @Override public CompletableFuture<V> asyncLoad(K key, Executor executor) {
167
        return asyncLoadAll(Set.of(key), executor)
×
168
            .thenApply(results -> results.get(key));
×
169
      }
170
      @Override public CompletableFuture<Map<K, V>> asyncLoadAll(
171
          Set<? extends K> keys, Executor executor) {
172
        requireNonNull(keys);
×
173
        requireNonNull(executor);
×
174
        @SuppressWarnings("unchecked")
175
        var future = (CompletableFuture<Map<K, V>>) mappingFunction.apply(keys, executor);
×
176
        return future;
×
177
      }
178
    };
179
  }
180
}
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