0
# Management and Monitoring
1
2
The Management and Monitoring system provides JMX integration for cache statistics, management operations, and runtime monitoring of cache performance and behavior. The system includes comprehensive statistics collection and JMX MBean registration for monitoring tools.
3
4
## Capabilities
5
6
### JCacheStatisticsMXBean
7
8
JMX MBean providing comprehensive cache statistics for monitoring cache performance and behavior.
9
10
```java { .api }
11
/**
12
* JMX MBean for cache statistics implementing JSR-107 CacheStatisticsMXBean
13
*/
14
public final class JCacheStatisticsMXBean implements CacheStatisticsMXBean {
15
16
/**
17
* Check if statistics collection is enabled
18
* @return true if statistics are being collected
19
*/
20
public boolean isEnabled();
21
22
/**
23
* Get the number of cache hits
24
* @return total number of successful cache retrievals
25
*/
26
public long getCacheHits();
27
28
/**
29
* Get the number of cache misses
30
* @return total number of failed cache retrievals
31
*/
32
public long getCacheMisses();
33
34
/**
35
* Get the total number of get operations
36
* @return total number of cache get operations (hits + misses)
37
*/
38
public long getCacheGets();
39
40
/**
41
* Get the number of cache puts
42
* @return total number of cache put operations
43
*/
44
public long getCachePuts();
45
46
/**
47
* Get the number of cache removals
48
* @return total number of cache remove operations
49
*/
50
public long getCacheRemovals();
51
52
/**
53
* Get the number of cache evictions
54
* @return total number of entries evicted from cache
55
*/
56
public long getCacheEvictions();
57
58
/**
59
* Get the average time for get operations in microseconds
60
* @return average get operation time
61
*/
62
public float getAverageGetTime();
63
64
/**
65
* Get the average time for put operations in microseconds
66
* @return average put operation time
67
*/
68
public float getAveragePutTime();
69
70
/**
71
* Get the average time for remove operations in microseconds
72
* @return average remove operation time
73
*/
74
public float getAverageRemoveTime();
75
76
/**
77
* Get the cache hit percentage
78
* @return percentage of successful cache retrievals (0-100)
79
*/
80
public float getCacheHitPercentage();
81
82
/**
83
* Get the cache miss percentage
84
* @return percentage of failed cache retrievals (0-100)
85
*/
86
public float getCacheMissPercentage();
87
}
88
```
89
90
**Usage Examples:**
91
92
```java
93
// Enable statistics on cache
94
CaffeineConfiguration<String, String> config = new CaffeineConfiguration<String, String>()
95
.setTypes(String.class, String.class)
96
.setStatisticsEnabled(true);
97
98
Cache<String, String> cache = cacheManager.createCache("monitoredCache", config);
99
100
// Statistics are automatically collected
101
cache.put("key1", "value1");
102
cache.put("key2", "value2");
103
String value = cache.get("key1"); // Hit
104
String missing = cache.get("key3"); // Miss
105
106
// Access statistics via JMX or programmatically
107
CacheStatisticsMXBean stats = cache.unwrap(CacheProxy.class)
108
.getConfiguration(CaffeineConfiguration.class)
109
.getStatisticsMXBean();
110
111
System.out.println("Cache hits: " + stats.getCacheHits());
112
System.out.println("Cache misses: " + stats.getCacheMisses());
113
System.out.println("Hit percentage: " + stats.getCacheHitPercentage() + "%");
114
```
115
116
### JCacheMXBean
117
118
JMX MBean for cache management operations and configuration access.
119
120
```java { .api }
121
/**
122
* JMX MBean for cache management implementing JSR-107 CacheMXBean
123
*/
124
public final class JCacheMXBean implements CacheMXBean {
125
126
/**
127
* Get the cache key type name
128
* @return fully qualified name of the key type
129
*/
130
public String getKeyType();
131
132
/**
133
* Get the cache value type name
134
* @return fully qualified name of the value type
135
*/
136
public String getValueType();
137
138
/**
139
* Check if read-through is enabled
140
* @return true if read-through is enabled
141
*/
142
public boolean isReadThrough();
143
144
/**
145
* Check if write-through is enabled
146
* @return true if write-through is enabled
147
*/
148
public boolean isWriteThrough();
149
150
/**
151
* Check if store-by-value is enabled
152
* @return true if store-by-value is enabled
153
*/
154
public boolean isStoreByValue();
155
156
/**
157
* Check if statistics collection is enabled
158
* @return true if statistics are enabled
159
*/
160
public boolean isStatisticsEnabled();
161
162
/**
163
* Check if management is enabled
164
* @return true if management is enabled
165
*/
166
public boolean isManagementEnabled();
167
}
168
```
169
170
### JmxRegistration
171
172
Utility for JMX MBean registration and unregistration with proper naming and lifecycle management.
173
174
```java { .api }
175
/**
176
* Utility for JMX MBean registration and unregistration
177
*/
178
public final class JmxRegistration {
179
180
/**
181
* MBean types for registration
182
*/
183
public enum MBeanType {
184
CONFIGURATION, STATISTICS
185
}
186
187
/**
188
* Register an MXBean for the specified cache
189
* @param cache the cache to register MBean for
190
* @param mxBean the MXBean instance to register
191
* @param mBeanType the type of MBean being registered
192
*/
193
public static void registerMxBean(Cache<?, ?> cache, Object mxBean, MBeanType mBeanType);
194
195
/**
196
* Unregister an MXBean for the specified cache
197
* @param cache the cache to unregister MBean for
198
* @param mBeanType the type of MBean being unregistered
199
*/
200
public static void unregisterMxBean(Cache<?, ?> cache, MBeanType mBeanType);
201
}
202
```
203
204
**Usage Examples:**
205
206
```java
207
Cache<String, String> cache = cacheManager.createCache("managedCache", config);
208
209
// Enable management (automatically registers MBeans)
210
cacheManager.enableManagement("managedCache", true);
211
cacheManager.enableStatistics("managedCache", true);
212
213
// Manual MBean registration (not typically needed)
214
JCacheMXBean managementBean = new JCacheMXBean(cache);
215
JmxRegistration.registerMxBean(cache, managementBean, JmxRegistration.MBeanType.CONFIGURATION);
216
217
// Access via JMX client or programmatically
218
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
219
ObjectName objectName = new ObjectName(
220
"javax.cache:type=CacheConfiguration" +
221
",CacheManager=" + cache.getCacheManager().getURI() +
222
",Cache=" + cache.getName());
223
224
String keyType = (String) mBeanServer.getAttribute(objectName, "KeyType");
225
Boolean isStoreByValue = (Boolean) mBeanServer.getAttribute(objectName, "StoreByValue");
226
```
227
228
### Statistics Configuration
229
230
Configure statistics collection behavior and granularity.
231
232
```java { .api }
233
// Enable standard JSR-107 statistics
234
CaffeineConfiguration<String, String> standardStats = new CaffeineConfiguration<String, String>()
235
.setStatisticsEnabled(true);
236
237
// Enable native Caffeine statistics for additional metrics
238
CaffeineConfiguration<String, String> nativeStats = new CaffeineConfiguration<String, String>()
239
.setStatisticsEnabled(true)
240
.setNativeStatisticsEnabled(true);
241
242
Cache<String, String> cache = cacheManager.createCache("statsCache", nativeStats);
243
```
244
245
### Monitoring Integration
246
247
Integration with monitoring systems and frameworks.
248
249
```java { .api }
250
// Micrometer integration example
251
MeterRegistry meterRegistry = new SimpleMeterRegistry();
252
253
Cache<String, String> cache = cacheManager.getCache("monitoredCache");
254
CacheStatisticsMXBean stats = /* get statistics bean */;
255
256
// Register metrics
257
Gauge.builder("cache.hits")
258
.description("Cache hit count")
259
.register(meterRegistry, stats, CacheStatisticsMXBean::getCacheHits);
260
261
Gauge.builder("cache.hit.ratio")
262
.description("Cache hit ratio")
263
.register(meterRegistry, stats, s -> s.getCacheHitPercentage() / 100.0);
264
265
Timer.builder("cache.get")
266
.description("Cache get operation time")
267
.register(meterRegistry);
268
```
269
270
### Performance Monitoring
271
272
Monitor cache performance characteristics and optimization opportunities.
273
274
```java { .api }
275
public class CachePerformanceMonitor {
276
private final CacheStatisticsMXBean statistics;
277
private final ScheduledExecutorService scheduler;
278
279
public CachePerformanceMonitor(Cache<?, ?> cache) {
280
this.statistics = cache.unwrap(CacheProxy.class)
281
.getStatistics();
282
this.scheduler = Executors.newScheduledThreadPool(1);
283
}
284
285
public void startMonitoring() {
286
scheduler.scheduleAtFixedRate(this::reportMetrics, 0, 60, TimeUnit.SECONDS);
287
}
288
289
private void reportMetrics() {
290
System.out.println("=== Cache Performance Report ===");
291
System.out.println("Hits: " + statistics.getCacheHits());
292
System.out.println("Misses: " + statistics.getCacheMisses());
293
System.out.println("Hit Ratio: " + String.format("%.2f%%", statistics.getCacheHitPercentage()));
294
System.out.println("Avg Get Time: " + String.format("%.2f μs", statistics.getAverageGetTime()));
295
System.out.println("Avg Put Time: " + String.format("%.2f μs", statistics.getAveragePutTime()));
296
System.out.println("Evictions: " + statistics.getCacheEvictions());
297
298
// Check for performance issues
299
if (statistics.getCacheHitPercentage() < 80.0f) {
300
System.out.println("WARNING: Low hit ratio detected!");
301
}
302
303
if (statistics.getAverageGetTime() > 1000.0f) {
304
System.out.println("WARNING: High get latency detected!");
305
}
306
}
307
}
308
```
309
310
### JMX Integration
311
312
Complete JMX integration for enterprise monitoring tools.
313
314
```java { .api }
315
// JMX ObjectName format for cache MBeans
316
// Configuration MBean:
317
// javax.cache:type=CacheConfiguration,CacheManager=<uri>,Cache=<name>
318
319
// Statistics MBean:
320
// javax.cache:type=CacheStatistics,CacheManager=<uri>,Cache=<name>
321
322
public class JmxCacheMonitor {
323
public void monitorCache(String cacheManagerUri, String cacheName) throws Exception {
324
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
325
326
// Access configuration MBean
327
ObjectName configName = new ObjectName(
328
"javax.cache:type=CacheConfiguration" +
329
",CacheManager=" + cacheManagerUri +
330
",Cache=" + cacheName);
331
332
// Access statistics MBean
333
ObjectName statsName = new ObjectName(
334
"javax.cache:type=CacheStatistics" +
335
",CacheManager=" + cacheManagerUri +
336
",Cache=" + cacheName);
337
338
// Query configuration
339
String keyType = (String) mBeanServer.getAttribute(configName, "KeyType");
340
String valueType = (String) mBeanServer.getAttribute(configName, "ValueType");
341
Boolean readThrough = (Boolean) mBeanServer.getAttribute(configName, "ReadThrough");
342
Boolean writeThrough = (Boolean) mBeanServer.getAttribute(configName, "WriteThrough");
343
344
// Query statistics
345
Long hits = (Long) mBeanServer.getAttribute(statsName, "CacheHits");
346
Long misses = (Long) mBeanServer.getAttribute(statsName, "CacheMisses");
347
Float hitPercentage = (Float) mBeanServer.getAttribute(statsName, "CacheHitPercentage");
348
Float averageGetTime = (Float) mBeanServer.getAttribute(statsName, "AverageGetTime");
349
350
System.out.println("Cache Configuration:");
351
System.out.println(" Key Type: " + keyType);
352
System.out.println(" Value Type: " + valueType);
353
System.out.println(" Read Through: " + readThrough);
354
System.out.println(" Write Through: " + writeThrough);
355
356
System.out.println("Cache Statistics:");
357
System.out.println(" Hits: " + hits);
358
System.out.println(" Misses: " + misses);
359
System.out.println(" Hit Percentage: " + hitPercentage + "%");
360
System.out.println(" Average Get Time: " + averageGetTime + " μs");
361
}
362
}
363
```
364
365
### Health Checks
366
367
Implement health checks for cache monitoring and alerting.
368
369
```java { .api }
370
public class CacheHealthCheck {
371
private final Cache<?, ?> cache;
372
private final CacheStatisticsMXBean statistics;
373
374
public CacheHealthCheck(Cache<?, ?> cache) {
375
this.cache = cache;
376
this.statistics = cache.unwrap(CacheProxy.class).getStatistics();
377
}
378
379
public HealthStatus checkHealth() {
380
if (cache.isClosed()) {
381
return HealthStatus.unhealthy("Cache is closed");
382
}
383
384
if (!statistics.isEnabled()) {
385
return HealthStatus.healthy("Cache operational (statistics disabled)");
386
}
387
388
float hitPercentage = statistics.getCacheHitPercentage();
389
float averageGetTime = statistics.getAverageGetTime();
390
391
if (hitPercentage < 50.0f) {
392
return HealthStatus.unhealthy("Low hit ratio: " + hitPercentage + "%");
393
}
394
395
if (averageGetTime > 5000.0f) {
396
return HealthStatus.unhealthy("High latency: " + averageGetTime + " μs");
397
}
398
399
return HealthStatus.healthy("Cache performing well");
400
}
401
}
402
```
403
404
### Alerting and Notifications
405
406
Set up alerting based on cache metrics and thresholds.
407
408
```java { .api }
409
public class CacheAlerting {
410
public void setupAlerts(Cache<?, ?> cache) {
411
CacheStatisticsMXBean stats = cache.unwrap(CacheProxy.class).getStatistics();
412
413
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
414
415
scheduler.scheduleAtFixedRate(() -> {
416
try {
417
checkHitRatio(stats);
418
checkLatency(stats);
419
checkEvictionRate(stats);
420
} catch (Exception e) {
421
sendAlert("Cache monitoring error: " + e.getMessage());
422
}
423
}, 0, 5, TimeUnit.MINUTES);
424
}
425
426
private void checkHitRatio(CacheStatisticsMXBean stats) {
427
float hitRatio = stats.getCacheHitPercentage();
428
if (hitRatio < 80.0f) {
429
sendAlert("Cache hit ratio below threshold: " + hitRatio + "%");
430
}
431
}
432
433
private void checkLatency(CacheStatisticsMXBean stats) {
434
float avgGetTime = stats.getAverageGetTime();
435
if (avgGetTime > 1000.0f) {
436
sendAlert("Cache latency above threshold: " + avgGetTime + " μs");
437
}
438
}
439
440
private void checkEvictionRate(CacheStatisticsMXBean stats) {
441
long evictions = stats.getCacheEvictions();
442
long gets = stats.getCacheGets();
443
444
if (gets > 0 && (evictions * 100.0 / gets) > 10.0) {
445
sendAlert("High eviction rate detected: " +
446
String.format("%.2f%%", evictions * 100.0 / gets));
447
}
448
}
449
450
private void sendAlert(String message) {
451
// Send alert to monitoring system
452
System.err.println("ALERT: " + message);
453
}
454
}
455
```