0
# Cache Construction
1
2
The Caffeine builder provides a comprehensive fluent API for configuring cache instances. The builder pattern allows combining multiple configuration options and terminates with methods that create the actual cache instances.
3
4
## Builder Factory Methods
5
6
```java { .api }
7
public static Caffeine<Object, Object> newBuilder()
8
public static Caffeine<Object, Object> from(CaffeineSpec spec)
9
public static Caffeine<Object, Object> from(String spec)
10
```
11
12
### Usage Example
13
14
```java
15
// Basic builder creation
16
Caffeine<Object, Object> builder = Caffeine.newBuilder();
17
18
// From specification string
19
Caffeine<Object, Object> builder2 = Caffeine.from("maximumSize=10000,expireAfterWrite=10m");
20
21
// From specification object
22
CaffeineSpec spec = CaffeineSpec.parse("maximumSize=10000,expireAfterWrite=10m");
23
Caffeine<Object, Object> builder3 = Caffeine.from(spec);
24
```
25
26
## Size and Weight Configuration
27
28
Configure cache capacity using either entry count or custom weights.
29
30
```java { .api }
31
public Caffeine<K, V> initialCapacity(int initialCapacity)
32
public Caffeine<K, V> maximumSize(long maximumSize)
33
public Caffeine<K, V> maximumWeight(long maximumWeight)
34
public <K1, V1> Caffeine<K1, V1> weigher(Weigher<? super K1, ? super V1> weigher)
35
```
36
37
### Usage Example
38
39
```java
40
// Size-based eviction
41
Cache<String, String> sizeCache = Caffeine.newBuilder()
42
.initialCapacity(100)
43
.maximumSize(10_000)
44
.build();
45
46
// Weight-based eviction with custom weigher
47
Cache<String, String> weightCache = Caffeine.newBuilder()
48
.maximumWeight(100_000)
49
.weigher((key, value) -> key.length() + value.length())
50
.build();
51
```
52
53
**Constraints**: Cannot use both `maximumSize()` and `maximumWeight()` on the same builder.
54
55
## Reference Strength Configuration
56
57
Configure memory management behavior for keys and values.
58
59
```java { .api }
60
public Caffeine<K, V> weakKeys()
61
public Caffeine<K, V> weakValues()
62
public Caffeine<K, V> softValues()
63
```
64
65
### Usage Example
66
67
```java
68
// Weak references for keys (allows GC when no other references exist)
69
Cache<String, String> weakKeyCache = Caffeine.newBuilder()
70
.maximumSize(1000)
71
.weakKeys()
72
.build();
73
74
// Soft references for values (GC under memory pressure)
75
Cache<String, LargeObject> softValueCache = Caffeine.newBuilder()
76
.maximumSize(1000)
77
.softValues()
78
.build();
79
```
80
81
**Constraints**:
82
- Weak/soft references use identity comparison (==) instead of equals()
83
- Cannot use weak/soft values with async caches
84
85
## Expiration Configuration
86
87
Configure time-based entry expiration using fixed or variable policies.
88
89
```java { .api }
90
// Fixed expiration policies
91
public Caffeine<K, V> expireAfterWrite(Duration duration)
92
public Caffeine<K, V> expireAfterWrite(long duration, TimeUnit unit)
93
public Caffeine<K, V> expireAfterAccess(Duration duration)
94
public Caffeine<K, V> expireAfterAccess(long duration, TimeUnit unit)
95
96
// Variable expiration policy
97
public <K1, V1> Caffeine<K1, V1> expireAfter(Expiry<? super K1, ? super V1> expiry)
98
```
99
100
### Usage Example
101
102
```java
103
// Fixed expiration after write
104
Cache<String, String> writeExpireCache = Caffeine.newBuilder()
105
.maximumSize(1000)
106
.expireAfterWrite(Duration.ofMinutes(10))
107
.build();
108
109
// Fixed expiration after access
110
Cache<String, String> accessExpireCache = Caffeine.newBuilder()
111
.maximumSize(1000)
112
.expireAfterAccess(30, TimeUnit.MINUTES)
113
.build();
114
115
// Variable expiration based on entry characteristics
116
Cache<String, String> variableExpireCache = Caffeine.newBuilder()
117
.maximumSize(1000)
118
.expireAfter(Expiry.creating((key, value) ->
119
key.startsWith("temp_") ? Duration.ofMinutes(5) : Duration.ofHours(1)))
120
.build();
121
```
122
123
**Constraints**: Cannot mix `expireAfter(Expiry)` with other expiration methods.
124
125
## Refresh Configuration
126
127
Configure automatic background refresh for loading caches.
128
129
```java { .api }
130
public Caffeine<K, V> refreshAfterWrite(Duration duration)
131
public Caffeine<K, V> refreshAfterWrite(long duration, TimeUnit unit)
132
```
133
134
### Usage Example
135
136
```java
137
LoadingCache<String, String> refreshingCache = Caffeine.newBuilder()
138
.maximumSize(1000)
139
.refreshAfterWrite(Duration.ofMinutes(5))
140
.build(key -> fetchFromDatabase(key));
141
142
// Old value remains available during refresh
143
String value = refreshingCache.get("key"); // Returns cached value while refreshing
144
```
145
146
**Constraints**: Only applicable to LoadingCache and AsyncLoadingCache instances.
147
148
## Execution and Scheduling Configuration
149
150
Configure threading and scheduling for cache operations.
151
152
```java { .api }
153
public Caffeine<K, V> executor(Executor executor)
154
public Caffeine<K, V> scheduler(Scheduler scheduler)
155
public Caffeine<K, V> ticker(Ticker ticker)
156
```
157
158
### Usage Example
159
160
```java
161
// Custom executor for async operations
162
ExecutorService customExecutor = Executors.newFixedThreadPool(4);
163
Cache<String, String> customExecCache = Caffeine.newBuilder()
164
.executor(customExecutor)
165
.maximumSize(1000)
166
.build();
167
168
// Custom scheduler for maintenance
169
ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1);
170
Cache<String, String> customSchedCache = Caffeine.newBuilder()
171
.scheduler(Scheduler.forScheduledExecutorService(scheduledExecutor))
172
.expireAfterWrite(Duration.ofMinutes(10))
173
.maximumSize(1000)
174
.build();
175
176
// Custom ticker for testing
177
Cache<String, String> testCache = Caffeine.newBuilder()
178
.ticker(Ticker.disabledTicker()) // Always returns 0
179
.expireAfterWrite(Duration.ofMinutes(10))
180
.maximumSize(1000)
181
.build();
182
```
183
184
## Listener Configuration
185
186
Configure callbacks for cache entry removal events.
187
188
```java { .api }
189
public <K1, V1> Caffeine<K1, V1> evictionListener(RemovalListener<? super K1, ? super V1> evictionListener)
190
public <K1, V1> Caffeine<K1, V1> removalListener(RemovalListener<? super K1, ? super V1> removalListener)
191
```
192
193
### Usage Example
194
195
```java
196
// Eviction listener (called during cache operations)
197
Cache<String, String> evictionListenerCache = Caffeine.newBuilder()
198
.maximumSize(1000)
199
.evictionListener((key, value, cause) -> {
200
if (cause.wasEvicted()) {
201
System.out.println("Evicted: " + key + " -> " + value + " (" + cause + ")");
202
}
203
})
204
.build();
205
206
// Removal listener (called asynchronously)
207
Cache<String, String> removalListenerCache = Caffeine.newBuilder()
208
.maximumSize(1000)
209
.removalListener((key, value, cause) -> {
210
System.out.println("Removed: " + key + " -> " + value + " (" + cause + ")");
211
// Cleanup resources, log to external system, etc.
212
})
213
.build();
214
```
215
216
**Difference**:
217
- `evictionListener`: Called synchronously during cache operations
218
- `removalListener`: Called asynchronously for all removal events
219
220
## Statistics Configuration
221
222
Enable cache performance tracking and statistics collection.
223
224
```java { .api }
225
public Caffeine<K, V> recordStats()
226
public Caffeine<K, V> recordStats(Supplier<? extends StatsCounter> statsCounterSupplier)
227
```
228
229
### Usage Example
230
231
```java
232
// Basic statistics recording
233
Cache<String, String> statsCache = Caffeine.newBuilder()
234
.maximumSize(1000)
235
.recordStats()
236
.build();
237
238
CacheStats stats = statsCache.stats();
239
System.out.println("Hit rate: " + stats.hitRate());
240
241
// Custom statistics counter
242
Cache<String, String> customStatsCache = Caffeine.newBuilder()
243
.maximumSize(1000)
244
.recordStats(ConcurrentStatsCounter::new)
245
.build();
246
```
247
248
## Terminal Methods
249
250
Create the actual cache instances from the configured builder.
251
252
```java { .api }
253
// Synchronous cache creation
254
public <K1 extends K, V1 extends V> Cache<K1, V1> build()
255
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(CacheLoader<? super K1, V1> loader)
256
257
// Asynchronous cache creation
258
public <K1 extends K, V1 extends V> AsyncCache<K1, V1> buildAsync()
259
public <K1 extends K, V1 extends V> AsyncLoadingCache<K1, V1> buildAsync(CacheLoader<? super K1, V1> loader)
260
public <K1 extends K, V1 extends V> AsyncLoadingCache<K1, V1> buildAsync(AsyncCacheLoader<? super K1, V1> loader)
261
```
262
263
### Usage Example
264
265
```java
266
// Manual cache
267
Cache<String, String> manualCache = Caffeine.newBuilder()
268
.maximumSize(1000)
269
.build();
270
271
// Loading cache with CacheLoader
272
LoadingCache<String, String> loadingCache = Caffeine.newBuilder()
273
.maximumSize(1000)
274
.build(key -> "loaded_" + key);
275
276
// Async cache
277
AsyncCache<String, String> asyncCache = Caffeine.newBuilder()
278
.maximumSize(1000)
279
.buildAsync();
280
281
// Async loading cache with CacheLoader
282
AsyncLoadingCache<String, String> asyncLoadingCache = Caffeine.newBuilder()
283
.maximumSize(1000)
284
.buildAsync(key -> "async_loaded_" + key);
285
286
// Async loading cache with AsyncCacheLoader
287
AsyncLoadingCache<String, String> asyncLoaderCache = Caffeine.newBuilder()
288
.maximumSize(1000)
289
.buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> "async_" + key, executor));
290
```
291
292
## Configuration Validation
293
294
The builder performs runtime validation to prevent incompatible configuration combinations:
295
296
- **Size vs Weight**: Cannot use both `maximumSize()` and `maximumWeight()`
297
- **Expiration Exclusivity**: Cannot mix `expireAfter(Expiry)` with fixed expiration methods
298
- **Async Limitations**: Cannot use weak/soft values with async caches
299
- **Refresh Requirements**: `refreshAfterWrite()` only works with loading cache types
300
301
Attempting incompatible combinations will throw `IllegalStateException` during cache creation.