-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCacheStats.java
More file actions
34 lines (27 loc) · 1.13 KB
/
CacheStats.java
File metadata and controls
34 lines (27 loc) · 1.13 KB
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
package lrucache;
import java.util.concurrent.atomic.AtomicLong;
/**
* Lock-free hit/miss/eviction counters.
* AtomicLong means reads and writes to these counters never need a lock,
* keeping the hot path (get/put) as fast as possible.
*/
public class CacheStats {
private final AtomicLong hits = new AtomicLong();
private final AtomicLong misses = new AtomicLong();
private final AtomicLong evictions = new AtomicLong();
void recordHit() { hits.incrementAndGet(); }
void recordMiss() { misses.incrementAndGet(); }
void recordEviction() { evictions.incrementAndGet(); }
public long getHits() { return hits.get(); }
public long getMisses() { return misses.get(); }
public long getEvictions() { return evictions.get(); }
public double hitRate() {
long total = hits.get() + misses.get();
return total == 0 ? 0.0 : (double) hits.get() / total;
}
@Override
public String toString() {
return String.format("CacheStats{hits=%d, misses=%d, evictions=%d, hitRate=%.2f%%}",
getHits(), getMisses(), getEvictions(), hitRate() * 100);
}
}