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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
import java.util.*;
public class LFUCache { private static final int DEFAULT_MAX_SIZE = 3; private int capacity = DEFAULT_MAX_SIZE; private final Map<Integer, HitRate> cache = new HashMap<Integer, HitRate>(); private final Map<Integer, Integer> KV = new HashMap<Integer, Integer>();
public LFUCache(int capacity) { this.capacity = capacity; }
public void set(int key, int value) { Integer v = KV.get(key); if (v == null) { if (cache.size() == capacity) { Integer k = getKickedKey(); KV.remove(k); cache.remove(k); } cache.put(key, new HitRate(key, 1, System.nanoTime())); } else { HitRate hitRate = cache.get(key); hitRate.hitCount += 1; hitRate.lastTime = System.nanoTime(); } KV.put(key, value); }
public int get(int key) { Integer v = KV.get(key); if (v != null) { HitRate hitRate = cache.get(key); hitRate.hitCount += 1; hitRate.lastTime = System.nanoTime(); return v; } return -1; } private Integer getKickedKey() { HitRate min = Collections.min(cache.values()); return min.key; }
class HitRate implements Comparable<HitRate> { Integer key; Integer hitCount; Long lastTime;
public HitRate(Integer key, Integer hitCount, Long lastTime) { this.key = key; this.hitCount = hitCount; this.lastTime = lastTime; }
public int compareTo(HitRate o) { int hr = hitCount.compareTo(o.hitCount); return hr != 0 ? hr : lastTime.compareTo(o.lastTime); } }
public static void main(String[] as) throws Exception { LFUCache cache = new LFUCache(3); cache.set(2, 2); cache.set(1, 1);
System.out.println(cache.get(2)); System.out.println(cache.get(1)); System.out.println(cache.get(2));
cache.set(3, 3); cache.set(4, 4);
System.out.println(cache.get(3)); System.out.println(cache.get(2)); System.out.println(cache.get(1)); System.out.println(cache.get(4));
} }
|