0
# Cache Operations
1
2
The Cache Operations system provides the complete JSR-107 Cache interface implementation with both synchronous and asynchronous operations. The `CacheProxy` and `LoadingCacheProxy` classes implement all standard caching operations backed by Caffeine's high-performance cache engine.
3
4
## Capabilities
5
6
### Basic Cache Operations
7
8
Core caching functionality for storing, retrieving, and checking cache entries.
9
10
```java { .api }
11
/**
12
* Get value by key, returns null if not present
13
* @param key the key to look up
14
* @return the associated value or null
15
*/
16
public @Nullable V get(K key);
17
18
/**
19
* Get multiple values by keys
20
* @param keys the set of keys to look up
21
* @return map of found key-value pairs
22
*/
23
public Map<K, V> getAll(Set<? extends K> keys);
24
25
/**
26
* Check if a key exists in the cache
27
* @param key the key to check
28
* @return true if key exists and hasn't expired
29
*/
30
public boolean containsKey(K key);
31
32
/**
33
* Store a key-value pair in the cache
34
* @param key the key to store
35
* @param value the value to associate with the key
36
*/
37
public void put(K key, V value);
38
39
/**
40
* Store multiple key-value pairs in the cache
41
* @param map the map of key-value pairs to store
42
*/
43
public void putAll(Map<? extends K, ? extends V> map);
44
45
/**
46
* Store key-value pair only if key is not already present
47
* @param key the key to store
48
* @param value the value to associate with the key
49
* @return true if the key was absent and value was stored
50
*/
51
public boolean putIfAbsent(K key, V value);
52
```
53
54
**Usage Examples:**
55
56
```java
57
Cache<String, Integer> cache = cacheManager.getCache("numbers", String.class, Integer.class);
58
59
// Basic operations
60
cache.put("one", 1);
61
cache.put("two", 2);
62
63
Integer value = cache.get("one"); // Returns 1
64
boolean exists = cache.containsKey("two"); // Returns true
65
66
// Bulk operations
67
Map<String, Integer> batch = Map.of(
68
"three", 3,
69
"four", 4,
70
"five", 5
71
);
72
cache.putAll(batch);
73
74
Set<String> keys = Set.of("one", "three", "five");
75
Map<String, Integer> results = cache.getAll(keys);
76
77
// Conditional put
78
boolean added = cache.putIfAbsent("six", 6); // Returns true
79
boolean notAdded = cache.putIfAbsent("six", 60); // Returns false, value unchanged
80
```
81
82
### Atomic Operations
83
84
Thread-safe atomic operations that combine read and write operations.
85
86
```java { .api }
87
/**
88
* Atomically get current value and store new value
89
* @param key the key to update
90
* @param value the new value to store
91
* @return the previous value or null if key was absent
92
*/
93
public @Nullable V getAndPut(K key, V value);
94
95
/**
96
* Atomically get current value and remove the entry
97
* @param key the key to remove
98
* @return the previous value or null if key was absent
99
*/
100
public V getAndRemove(K key);
101
102
/**
103
* Atomically get current value and replace with new value
104
* @param key the key to replace
105
* @param value the new value to store
106
* @return the previous value or null if key was absent
107
*/
108
public V getAndReplace(K key, V value);
109
110
/**
111
* Replace value only if current value equals expected value
112
* @param key the key to replace
113
* @param oldValue the expected current value
114
* @param newValue the new value to store
115
* @return true if replacement occurred
116
*/
117
public boolean replace(K key, V oldValue, V newValue);
118
119
/**
120
* Replace value only if key is currently mapped to some value
121
* @param key the key to replace
122
* @param value the new value to store
123
* @return true if replacement occurred
124
*/
125
public boolean replace(K key, V value);
126
```
127
128
**Usage Examples:**
129
130
```java
131
Cache<String, AtomicInteger> counters = cacheManager.getCache("counters", String.class, AtomicInteger.class);
132
133
// Initialize counter
134
counters.put("requests", new AtomicInteger(0));
135
136
// Atomic get-and-update operations
137
AtomicInteger oldCounter = counters.getAndPut("requests", new AtomicInteger(1));
138
AtomicInteger removedCounter = counters.getAndRemove("requests");
139
140
// Conditional replacement
141
counters.put("status", new AtomicInteger(0));
142
boolean replaced = counters.replace("status", new AtomicInteger(0), new AtomicInteger(1));
143
144
// Simple replacement
145
boolean updated = counters.replace("status", new AtomicInteger(2));
146
```
147
148
### Removal Operations
149
150
Various methods for removing entries from the cache.
151
152
```java { .api }
153
/**
154
* Remove entry by key
155
* @param key the key to remove
156
* @return true if key was present and removed
157
*/
158
public boolean remove(K key);
159
160
/**
161
* Remove entry only if current value equals expected value
162
* @param key the key to remove
163
* @param oldValue the expected current value
164
* @return true if removal occurred
165
*/
166
public boolean remove(K key, V oldValue);
167
168
/**
169
* Remove multiple entries by keys
170
* @param keys the set of keys to remove
171
*/
172
public void removeAll(Set<? extends K> keys);
173
174
/**
175
* Remove all entries from the cache
176
*/
177
public void removeAll();
178
179
/**
180
* Clear all entries from the cache without triggering listeners
181
*/
182
public void clear();
183
```
184
185
**Usage Examples:**
186
187
```java
188
Cache<String, String> cache = cacheManager.getCache("data", String.class, String.class);
189
190
// Populate cache
191
cache.putAll(Map.of("key1", "value1", "key2", "value2", "key3", "value3"));
192
193
// Remove single entry
194
boolean removed = cache.remove("key1"); // Returns true
195
196
// Conditional removal
197
boolean conditionalRemove = cache.remove("key2", "value2"); // Returns true
198
boolean failedRemove = cache.remove("key3", "wrongValue"); // Returns false
199
200
// Bulk removal
201
cache.removeAll(Set.of("key2", "key3"));
202
203
// Remove all entries
204
cache.removeAll(); // Triggers entry removed events
205
206
// Clear cache (no events)
207
cache.clear();
208
```
209
210
### Asynchronous Loading
211
212
Support for asynchronous cache loading with completion callbacks.
213
214
```java { .api }
215
/**
216
* Asynchronously load multiple entries, optionally replacing existing values
217
* @param keys the set of keys to load
218
* @param replaceExistingValues whether to replace existing cached values
219
* @param completionListener callback for completion or failure notification
220
*/
221
public void loadAll(Set<? extends K> keys,
222
boolean replaceExistingValues,
223
CompletionListener completionListener);
224
```
225
226
**Usage Examples:**
227
228
```java
229
Cache<String, User> userCache = cacheManager.getCache("users", String.class, User.class);
230
231
// Asynchronous loading with completion listener
232
Set<String> userIds = Set.of("user1", "user2", "user3");
233
234
userCache.loadAll(userIds, false, new CompletionListener() {
235
@Override
236
public void onCompletion() {
237
System.out.println("Loading completed successfully");
238
}
239
240
@Override
241
public void onException(Exception e) {
242
System.err.println("Loading failed: " + e.getMessage());
243
}
244
});
245
246
// Loading with replacement
247
userCache.loadAll(userIds, true, null); // No completion listener
248
```
249
250
### Entry Processing
251
252
Atomic entry processing operations for complex cache manipulations.
253
254
```java { .api }
255
/**
256
* Atomically process a single cache entry
257
* @param key the key to process
258
* @param entryProcessor the processor to apply
259
* @param arguments additional arguments for the processor
260
* @return result from the entry processor
261
*/
262
public <T> @Nullable T invoke(K key, EntryProcessor<K, V, T> entryProcessor, Object... arguments);
263
264
/**
265
* Atomically process multiple cache entries
266
* @param keys the set of keys to process
267
* @param entryProcessor the processor to apply
268
* @param arguments additional arguments for the processor
269
* @return map of processing results
270
*/
271
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys,
272
EntryProcessor<K, V, T> entryProcessor,
273
Object... arguments);
274
```
275
276
**Usage Examples:**
277
278
```java
279
Cache<String, Integer> cache = cacheManager.getCache("counters", String.class, Integer.class);
280
281
// Entry processor to increment counter
282
EntryProcessor<String, Integer, Integer> incrementProcessor =
283
(entry, arguments) -> {
284
Integer current = entry.getValue();
285
if (current == null) {
286
current = 0;
287
}
288
Integer newValue = current + 1;
289
entry.setValue(newValue);
290
return newValue;
291
};
292
293
// Process single entry
294
Integer result = cache.invoke("counter1", incrementProcessor);
295
296
// Process multiple entries
297
Set<String> keys = Set.of("counter1", "counter2", "counter3");
298
Map<String, EntryProcessorResult<Integer>> results =
299
cache.invokeAll(keys, incrementProcessor);
300
301
// Handle results
302
for (Map.Entry<String, EntryProcessorResult<Integer>> entry : results.entrySet()) {
303
try {
304
Integer value = entry.getValue().get();
305
System.out.println(entry.getKey() + " = " + value);
306
} catch (EntryProcessorException e) {
307
System.err.println("Processing failed for " + entry.getKey() + ": " + e.getMessage());
308
}
309
}
310
```
311
312
### LoadingCacheProxy
313
314
Extended cache implementation with automatic loading capabilities.
315
316
```java { .api }
317
/**
318
* Extended cache that automatically loads missing entries using configured CacheLoader
319
*/
320
public final class LoadingCacheProxy<K, V> extends CacheProxy<K, V> {
321
/**
322
* Get value by key, loading if necessary using the configured CacheLoader
323
* @param key the key to look up
324
* @return the associated value (loaded if not present)
325
* @throws CacheException if loading fails
326
*/
327
@Override
328
public @Nullable V get(K key);
329
330
/**
331
* Get multiple values by keys, loading missing entries as needed
332
* @param keys the set of keys to look up
333
* @return map of key-value pairs (missing entries are loaded)
334
* @throws CacheException if loading fails
335
*/
336
@Override
337
public Map<K, V> getAll(Set<? extends K> keys);
338
}
339
```
340
341
**Usage Examples:**
342
343
```java
344
// Configure cache with loader
345
CaffeineConfiguration<String, User> config = new CaffeineConfiguration<String, User>()
346
.setTypes(String.class, User.class)
347
.setCacheLoaderFactory(() -> new DatabaseUserLoader())
348
.setReadThrough(true);
349
350
Cache<String, User> userCache = cacheManager.createCache("users", config);
351
352
// Automatic loading on cache miss
353
User user = userCache.get("user123"); // Loads from database if not cached
354
355
// Bulk loading
356
Set<String> userIds = Set.of("user1", "user2", "user3");
357
Map<String, User> users = userCache.getAll(userIds); // Loads missing users
358
```
359
360
### Cache Metadata
361
362
Access to cache metadata and administrative operations.
363
364
```java { .api }
365
/**
366
* Get the cache name
367
* @return the name of this cache
368
*/
369
public String getName();
370
371
/**
372
* Get the associated cache manager
373
* @return the CacheManager that created this cache
374
*/
375
public CacheManager getCacheManager();
376
377
/**
378
* Check if the cache is closed
379
* @return true if the cache has been closed
380
*/
381
public boolean isClosed();
382
383
/**
384
* Close the cache and release resources
385
*/
386
public void close();
387
388
/**
389
* Get cache configuration
390
* @param clazz the configuration class to retrieve
391
* @return immutable copy of the configuration
392
*/
393
public <C extends Configuration<K, V>> C getConfiguration(Class<C> clazz);
394
395
/**
396
* Unwrap cache to specific implementation type
397
* @param clazz the class to unwrap to
398
* @return unwrapped instance
399
*/
400
public <T> T unwrap(Class<T> clazz);
401
402
/**
403
* Get iterator over cache entries
404
* @return iterator for cache entries
405
*/
406
public Iterator<Cache.Entry<K, V>> iterator();
407
```