-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
CaffeinatedGuavaLoadingCache.java
249 lines (224 loc) · 7.88 KB
/
CaffeinatedGuavaLoadingCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
* Copyright 2015 Ben Manes. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.benmanes.caffeine.guava;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import org.checkerframework.checker.nullness.qual.Nullable;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
/**
* A Caffeine-backed loading cache through a Guava facade.
*
* @author ben.manes@gmail.com (Ben Manes)
*/
@SuppressWarnings("serial")
final class CaffeinatedGuavaLoadingCache<K, V>
extends CaffeinatedGuavaCache<K, V> implements LoadingCache<K, V> {
private static final ThreadLocal<Boolean> nullBulkLoad =
ThreadLocal.withInitial(() -> Boolean.FALSE);
private static final long serialVersionUID = 1L;
private final com.github.benmanes.caffeine.cache.LoadingCache<K, V> cache;
CaffeinatedGuavaLoadingCache(com.github.benmanes.caffeine.cache.LoadingCache<K, V> cache) {
super(cache);
this.cache = cache;
}
@Override
@SuppressWarnings({"PMD.PreserveStackTrace", "NullAway"})
public V get(K key) throws ExecutionException {
requireNonNull(key);
try {
return cache.get(key);
} catch (InvalidCacheLoadException e) {
throw e;
} catch (CacheLoaderException e) {
throw new ExecutionException(e.getCause());
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
}
}
@Override
@SuppressWarnings({"PMD.PreserveStackTrace",
"PMD.AvoidCatchingNPE", "NullAway", "CatchingUnchecked"})
public V getUnchecked(K key) {
try {
return cache.get(key);
} catch (NullPointerException | InvalidCacheLoadException e) {
throw e;
} catch (CacheLoaderException e) {
throw new UncheckedExecutionException(e.getCause());
} catch (Exception e) {
throw new UncheckedExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
}
}
@Override
@SuppressWarnings({"PMD.PreserveStackTrace", "PMD.AvoidCatchingNPE", "CatchingUnchecked"})
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
try {
Map<K, V> result = cache.getAll(keys);
if (nullBulkLoad.get()) {
nullBulkLoad.set(false);
throw new InvalidCacheLoadException("null key or value");
}
for (K key : keys) {
if (!result.containsKey(key)) {
throw new InvalidCacheLoadException("loadAll failed to return a value for " + key);
}
}
return ImmutableMap.copyOf(result);
} catch (NullPointerException | InvalidCacheLoadException e) {
throw e;
} catch (CacheLoaderException e) {
throw new ExecutionException(e.getCause());
} catch (Exception e) {
throw new UncheckedExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
}
}
@Override
@SuppressWarnings({"deprecation", "NullAway"})
public V apply(K key) {
return cache.get(key);
}
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void refresh(K key) {
cache.refresh(key);
}
static class SingleLoader<K, V> implements CacheLoader<K, V>, Serializable {
private static final long serialVersionUID = 1L;
final com.google.common.cache.CacheLoader<K, V> cacheLoader;
SingleLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
this.cacheLoader = requireNonNull(cacheLoader);
}
@Override
public V load(K key) throws Exception {
try {
V value = cacheLoader.load(key);
if (value == null) {
throw new InvalidCacheLoadException("null value");
}
return value;
} catch (RuntimeException | Error e) {
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CacheLoaderException(e);
} catch (Exception e) {
throw new CacheLoaderException(e);
}
}
@Override
public CompletableFuture<V> asyncReload(K key, V oldValue, Executor executor) {
var future = new CompletableFuture<V>();
try {
ListenableFuture<V> reload = cacheLoader.reload(key, oldValue);
if (reload == null) {
future.completeExceptionally(new InvalidCacheLoadException("null value"));
} else {
Futures.addCallback(reload, new FutureCompleter<>(future), Runnable::run);
}
} catch (Throwable t) {
future.completeExceptionally(t);
}
return future;
}
}
static final class BulkLoader<K, V> extends SingleLoader<K, V> {
private static final long serialVersionUID = 1L;
BulkLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
super(cacheLoader);
}
@Override
public Map<K, V> loadAll(Set<? extends K> keys) {
try {
Map<K, V> loaded = cacheLoader.loadAll(keys);
if (loaded == null) {
throw new InvalidCacheLoadException("null map");
}
Map<K, V> result = new HashMap<>(loaded.size(), /* load factor */ 1.0f);
loaded.forEach((key, value) -> {
if ((key == null) || (value == null)) {
nullBulkLoad.set(true);
} else {
result.put(key, value);
}
});
return result;
} catch (RuntimeException | Error e) {
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CacheLoaderException(e);
} catch (Exception e) {
throw new CacheLoaderException(e);
}
}
}
static class ExternalizedSingleLoader<K, V> extends SingleLoader<K, V> {
ExternalizedSingleLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
super(cacheLoader);
}
@Override public V load(K key) throws Exception {
V value = cacheLoader.load(key);
if (value == null) {
throw new InvalidCacheLoadException("null value");
}
return value;
}
}
static final class ExternalizedBulkLoader<K, V> extends ExternalizedSingleLoader<K, V> {
ExternalizedBulkLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
super(cacheLoader);
}
@Override public Map<K, V> loadAll(Set<? extends K> keys) throws Exception {
return cacheLoader.loadAll(keys);
}
}
static final class FutureCompleter<V> implements FutureCallback<V> {
final CompletableFuture<V> future;
FutureCompleter(CompletableFuture<V> future) {
this.future = future;
}
@Override public void onSuccess(@Nullable V value) {
if (value == null) {
future.completeExceptionally(new InvalidCacheLoadException("null value"));
} else {
future.complete(value);
}
}
@Override public void onFailure(Throwable t) {
future.completeExceptionally(t);
}
}
}