0
# Caching System
1
2
Pluggable caching interfaces and implementations for Maven artifacts and POM files to improve performance.
3
4
## Capabilities
5
6
### Core Caching Interfaces
7
8
#### MavenArtifactCache
9
10
Interface for caching Maven artifacts with get/put operations.
11
12
```java { .api }
13
/**
14
* Interface for caching Maven artifacts to improve performance
15
*/
16
public interface MavenArtifactCache {
17
/**
18
* Get cached artifact content
19
* @param gav Group:Artifact:Version coordinate
20
* @return Cached artifact bytes or null if not cached
21
*/
22
@Nullable byte[] get(GroupArtifactVersion gav);
23
24
/**
25
* Cache artifact content
26
* @param gav Group:Artifact:Version coordinate
27
* @param artifact Artifact bytes to cache
28
*/
29
void put(GroupArtifactVersion gav, byte[] artifact);
30
31
/**
32
* Check if artifact is cached
33
* @param gav Group:Artifact:Version coordinate
34
* @return true if artifact is cached
35
*/
36
boolean contains(GroupArtifactVersion gav);
37
38
/**
39
* Remove artifact from cache
40
* @param gav Group:Artifact:Version coordinate
41
*/
42
void remove(GroupArtifactVersion gav);
43
44
/**
45
* Clear all cached artifacts
46
*/
47
void clear();
48
49
/**
50
* Get cache statistics
51
* @return Cache statistics information
52
*/
53
CacheStats getStats();
54
}
55
```
56
57
#### MavenPomCache
58
59
Interface for caching Maven POM files.
60
61
```java { .api }
62
/**
63
* Interface for caching Maven POM files to improve dependency resolution performance
64
*/
65
public interface MavenPomCache {
66
/**
67
* Get cached POM
68
* @param gav Group:Artifact:Version coordinate
69
* @return Cached POM or null if not cached
70
*/
71
@Nullable Pom get(GroupArtifactVersion gav);
72
73
/**
74
* Cache POM
75
* @param gav Group:Artifact:Version coordinate
76
* @param pom POM to cache
77
*/
78
void put(GroupArtifactVersion gav, Pom pom);
79
80
/**
81
* Check if POM is cached
82
* @param gav Group:Artifact:Version coordinate
83
* @return true if POM is cached
84
*/
85
boolean contains(GroupArtifactVersion gav);
86
87
/**
88
* Remove POM from cache
89
* @param gav Group:Artifact:Version coordinate
90
*/
91
void remove(GroupArtifactVersion gav);
92
93
/**
94
* Clear all cached POMs
95
*/
96
void clear();
97
98
/**
99
* Get cache size information
100
* @return Number of cached POMs
101
*/
102
int size();
103
}
104
```
105
106
### Artifact Cache Implementations
107
108
#### LocalMavenArtifactCache
109
110
File system-based artifact cache implementation.
111
112
```java { .api }
113
/**
114
* File system-based Maven artifact cache
115
* Stores artifacts in local directory structure matching Maven repository layout
116
*/
117
public class LocalMavenArtifactCache implements MavenArtifactCache {
118
/**
119
* Create cache with default Maven local repository location
120
*/
121
public LocalMavenArtifactCache();
122
123
/**
124
* Create cache with custom cache directory
125
* @param cacheDirectory Directory to store cached artifacts
126
*/
127
public LocalMavenArtifactCache(Path cacheDirectory);
128
129
/**
130
* Create cache with configuration
131
* @param cacheDirectory Directory to store cached artifacts
132
* @param maxSizeBytes Maximum cache size in bytes
133
* @param ttlHours Time-to-live for cached artifacts in hours
134
*/
135
public LocalMavenArtifactCache(Path cacheDirectory, long maxSizeBytes, int ttlHours);
136
}
137
```
138
139
**Usage Examples:**
140
141
```java
142
// Use default Maven local repository
143
LocalMavenArtifactCache cache = new LocalMavenArtifactCache();
144
145
// Use custom cache directory
146
Path customCache = Paths.get("/opt/maven-cache");
147
LocalMavenArtifactCache customCache = new LocalMavenArtifactCache(customCache);
148
149
// Use with size and TTL limits
150
LocalMavenArtifactCache limitedCache = new LocalMavenArtifactCache(
151
customCache,
152
1024 * 1024 * 1024L, // 1GB max size
153
24 * 7 // 1 week TTL
154
);
155
156
// Configure parser with cache
157
MavenParser parser = MavenParser.builder()
158
.cache(cache)
159
.build();
160
```
161
162
### POM Cache Implementations
163
164
#### InMemoryMavenPomCache
165
166
In-memory POM cache implementation with LRU eviction.
167
168
```java { .api }
169
/**
170
* In-memory Maven POM cache with LRU eviction policy
171
*/
172
public class InMemoryMavenPomCache implements MavenPomCache {
173
/**
174
* Create cache with default capacity (1000 POMs)
175
*/
176
public InMemoryMavenPomCache();
177
178
/**
179
* Create cache with custom capacity
180
* @param maxEntries Maximum number of POMs to cache
181
*/
182
public InMemoryMavenPomCache(int maxEntries);
183
184
/**
185
* Create cache with capacity and TTL
186
* @param maxEntries Maximum number of POMs to cache
187
* @param ttlMillis Time-to-live for cached POMs in milliseconds
188
*/
189
public InMemoryMavenPomCache(int maxEntries, long ttlMillis);
190
}
191
```
192
193
#### RocksdbMavenPomCache
194
195
RocksDB-based persistent POM cache implementation.
196
197
```java { .api }
198
/**
199
* RocksDB-based persistent Maven POM cache
200
* Provides high-performance persistent caching with compression
201
*/
202
public class RocksdbMavenPomCache implements MavenPomCache {
203
/**
204
* Create cache with default database location
205
*/
206
public RocksdbMavenPomCache();
207
208
/**
209
* Create cache with custom database path
210
* @param databasePath Path to RocksDB database directory
211
*/
212
public RocksdbMavenPomCache(Path databasePath);
213
214
/**
215
* Create cache with configuration
216
* @param databasePath Path to RocksDB database directory
217
* @param compressionType Compression algorithm to use
218
* @param maxBackgroundJobs Number of background compaction jobs
219
*/
220
public RocksdbMavenPomCache(Path databasePath, CompressionType compressionType, int maxBackgroundJobs);
221
222
/**
223
* Close the database connection
224
* Should be called when cache is no longer needed
225
*/
226
public void close();
227
}
228
```
229
230
#### CompositeMavenPomCache
231
232
Composite cache supporting multiple cache backends with layering.
233
234
```java { .api }
235
/**
236
* Composite Maven POM cache that layers multiple cache implementations
237
* Typically used with fast L1 cache (in-memory) and slower L2 cache (persistent)
238
*/
239
public class CompositeMavenPomCache implements MavenPomCache {
240
/**
241
* Create composite cache with multiple backends (ordered by priority)
242
* @param caches Cache implementations in priority order (L1, L2, etc.)
243
*/
244
public CompositeMavenPomCache(MavenPomCache... caches);
245
246
/**
247
* Create composite cache with configuration
248
* @param caches Cache implementations in priority order
249
* @param writeThrough Whether to write to all caches on put operations
250
*/
251
public CompositeMavenPomCache(boolean writeThrough, MavenPomCache... caches);
252
}
253
```
254
255
**Usage Examples:**
256
257
```java
258
// Simple in-memory cache
259
InMemoryMavenPomCache memoryCache = new InMemoryMavenPomCache(5000);
260
261
// Persistent RocksDB cache
262
Path dbPath = Paths.get("/opt/maven-pom-cache");
263
RocksdbMavenPomCache persistentCache = new RocksdbMavenPomCache(dbPath);
264
265
// Composite cache: fast memory + persistent storage
266
CompositeMavenPomCache compositeCache = new CompositeMavenPomCache(
267
true, // write-through
268
memoryCache, // L1: fast in-memory
269
persistentCache // L2: persistent storage
270
);
271
272
// Configure parser with composite cache
273
MavenParser parser = MavenParser.builder()
274
.pomCache(compositeCache)
275
.build();
276
277
// Remember to close persistent caches
278
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
279
persistentCache.close();
280
}));
281
```
282
283
### Cache Configuration
284
285
#### CacheStats
286
287
Cache statistics and monitoring information.
288
289
```java { .api }
290
/**
291
* Cache statistics for monitoring performance
292
*/
293
public class CacheStats {
294
/**
295
* Get cache hit count
296
*/
297
public long getHitCount();
298
299
/**
300
* Get cache miss count
301
*/
302
public long getMissCount();
303
304
/**
305
* Get cache hit rate (0.0 to 1.0)
306
*/
307
public double getHitRate();
308
309
/**
310
* Get total cache requests
311
*/
312
public long getRequestCount();
313
314
/**
315
* Get current cache size
316
*/
317
public long getSize();
318
319
/**
320
* Get maximum cache size
321
*/
322
public long getMaxSize();
323
324
/**
325
* Get eviction count
326
*/
327
public long getEvictionCount();
328
329
/**
330
* Get average load time in nanoseconds
331
*/
332
public double getAverageLoadPenalty();
333
}
334
```
335
336
#### Cache Event Listeners
337
338
```java { .api }
339
/**
340
* Interface for cache event notifications
341
*/
342
public interface CacheListener {
343
/**
344
* Called when item is added to cache
345
*/
346
void onCacheHit(GroupArtifactVersion gav);
347
348
/**
349
* Called when item is not found in cache
350
*/
351
void onCacheMiss(GroupArtifactVersion gav);
352
353
/**
354
* Called when item is evicted from cache
355
*/
356
void onEviction(GroupArtifactVersion gav, Object value);
357
358
/**
359
* Called when cache is cleared
360
*/
361
void onClear();
362
}
363
364
// Add listeners to cache implementations
365
public class MonitoredMavenPomCache implements MavenPomCache {
366
public void addListener(CacheListener listener);
367
public void removeListener(CacheListener listener);
368
}
369
```
370
371
### Cache Integration with MavenParser
372
373
#### Cache-Aware Parser Configuration
374
375
```java { .api }
376
/**
377
* Configure MavenParser with caching for optimal performance
378
*/
379
public class MavenParser.Builder {
380
/**
381
* Set artifact cache for parser
382
* @param cache Artifact cache implementation
383
* @return Builder for chaining
384
*/
385
public Builder cache(MavenArtifactCache cache);
386
387
/**
388
* Set POM cache for parser
389
* @param cache POM cache implementation
390
* @return Builder for chaining
391
*/
392
public Builder pomCache(MavenPomCache cache);
393
394
/**
395
* Enable/disable caching entirely
396
* @param enabled Whether to use caching
397
* @return Builder for chaining
398
*/
399
public Builder caching(boolean enabled);
400
}
401
```
402
403
**Complete Cache Setup Example:**
404
405
```java
406
// Set up comprehensive caching strategy
407
Path cacheRoot = Paths.get(System.getProperty("user.home"), ".maven-rewrite-cache");
408
409
// L1: Fast in-memory cache for frequently accessed items
410
InMemoryMavenPomCache l1Cache = new InMemoryMavenPomCache(
411
1000, // 1000 POMs
412
TimeUnit.HOURS.toMillis(1) // 1 hour TTL
413
);
414
415
// L2: Persistent cache for long-term storage
416
RocksdbMavenPomCache l2Cache = new RocksdbMavenPomCache(
417
cacheRoot.resolve("pom-cache"),
418
CompressionType.LZ4_COMPRESSION,
419
4 // 4 background compaction jobs
420
);
421
422
// Composite POM cache
423
CompositeMavenPomCache pomCache = new CompositeMavenPomCache(true, l1Cache, l2Cache);
424
425
// Artifact cache
426
LocalMavenArtifactCache artifactCache = new LocalMavenArtifactCache(
427
cacheRoot.resolve("artifact-cache"),
428
2L * 1024 * 1024 * 1024, // 2GB max size
429
24 * 7 // 1 week TTL
430
);
431
432
// Add monitoring
433
CacheListener monitor = new CacheListener() {
434
@Override
435
public void onCacheHit(GroupArtifactVersion gav) {
436
System.out.println("Cache hit: " + gav);
437
}
438
439
@Override
440
public void onCacheMiss(GroupArtifactVersion gav) {
441
System.out.println("Cache miss: " + gav);
442
}
443
444
@Override
445
public void onEviction(GroupArtifactVersion gav, Object value) {
446
System.out.println("Cache eviction: " + gav);
447
}
448
449
@Override
450
public void onClear() {
451
System.out.println("Cache cleared");
452
}
453
};
454
455
// Configure parser with caching
456
MavenParser parser = MavenParser.builder()
457
.pomCache(pomCache)
458
.cache(artifactCache)
459
.build();
460
461
// Parse with caching benefits
462
ExecutionContext ctx = new InMemoryExecutionContext();
463
List<SourceFile> parsed = parser.parse(ctx, pomXmlContent);
464
465
// Monitor cache performance
466
CacheStats stats = artifactCache.getStats();
467
System.out.println("Artifact Cache Stats:");
468
System.out.println(" Hit Rate: " + String.format("%.2f%%", stats.getHitRate() * 100));
469
System.out.println(" Total Requests: " + stats.getRequestCount());
470
System.out.println(" Cache Size: " + stats.getSize());
471
472
// Clean up
473
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
474
l2Cache.close();
475
}));
476
```
477
478
### Custom Cache Implementations
479
480
#### Implementing Custom Artifact Cache
481
482
```java
483
/**
484
* Example custom artifact cache implementation using external storage
485
*/
486
public class CloudMavenArtifactCache implements MavenArtifactCache {
487
private final CloudStorageClient client;
488
private final String bucketName;
489
private final Map<GroupArtifactVersion, Long> accessTimes = new ConcurrentHashMap<>();
490
491
public CloudMavenArtifactCache(CloudStorageClient client, String bucketName) {
492
this.client = client;
493
this.bucketName = bucketName;
494
}
495
496
@Override
497
public @Nullable byte[] get(GroupArtifactVersion gav) {
498
String key = keyFor(gav);
499
try {
500
byte[] data = client.getObject(bucketName, key);
501
accessTimes.put(gav, System.currentTimeMillis());
502
return data;
503
} catch (ObjectNotFoundException e) {
504
return null;
505
}
506
}
507
508
@Override
509
public void put(GroupArtifactVersion gav, byte[] artifact) {
510
String key = keyFor(gav);
511
client.putObject(bucketName, key, artifact);
512
accessTimes.put(gav, System.currentTimeMillis());
513
}
514
515
private String keyFor(GroupArtifactVersion gav) {
516
return gav.getGroupId().replace('.', '/') + "/" +
517
gav.getArtifactId() + "/" +
518
gav.getVersion() + "/" +
519
gav.getArtifactId() + "-" + gav.getVersion() + ".jar";
520
}
521
522
// Implement other interface methods...
523
}
524
```
525
526
#### Implementing Custom POM Cache
527
528
```java
529
/**
530
* Example custom POM cache with Redis backend
531
*/
532
public class RedisMavenPomCache implements MavenPomCache {
533
private final RedisClient redis;
534
private final ObjectMapper objectMapper;
535
private final Duration ttl;
536
537
public RedisMavenPomCache(RedisClient redis, Duration ttl) {
538
this.redis = redis;
539
this.ttl = ttl;
540
this.objectMapper = new ObjectMapper();
541
}
542
543
@Override
544
public @Nullable Pom get(GroupArtifactVersion gav) {
545
String key = keyFor(gav);
546
String json = redis.get(key);
547
if (json != null) {
548
try {
549
return objectMapper.readValue(json, Pom.class);
550
} catch (JsonProcessingException e) {
551
// Log error and return null
552
return null;
553
}
554
}
555
return null;
556
}
557
558
@Override
559
public void put(GroupArtifactVersion gav, Pom pom) {
560
String key = keyFor(gav);
561
try {
562
String json = objectMapper.writeValueAsString(pom);
563
redis.setex(key, ttl.getSeconds(), json);
564
} catch (JsonProcessingException e) {
565
// Log error
566
}
567
}
568
569
private String keyFor(GroupArtifactVersion gav) {
570
return "maven:pom:" + gav.getGroupId() + ":" + gav.getArtifactId() + ":" + gav.getVersion();
571
}
572
573
// Implement other interface methods...
574
}
575
```