base - 如何使用LinkedHashMap实现线程安全的LRU缓存?

269 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

static class Test1<K, V> extends LinkedHashMap<K, V> {

        private Integer max;

        public Test1 (Integer max) {
            super((int)Math.ceil(max/0.75)+1, 0.75F, true);
            this.max = max;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > max;
        }

        public static void main(String[] args) {
            Map<String, Object> test1 = Collections.synchronizedMap(new Test1<>(5));
            test1.put("1", "1");
            test1.put("2", "2");
            test1.put("3", "3");

            test1.forEach((a, b) -> System.out.println(a + " - " + b));
            System.out.println();

            test1.get("1");
            test1.put("4", "4");
            test1.put("5", "5");
            test1.put("7", "7");
            
            test1.forEach((a, b) -> System.out.println(a + " - " + b));
            System.out.println();

            test1.get("2");
            test1.get("3");
            test1.get("4");
            test1.put("6", "6");

            test1.forEach((a, b) -> System.out.println(a + " - " + b));
        }
    }

运行结果:

1 - 1
2 - 2
3 - 3

3 - 3
1 - 1
4 - 4
5 - 5
7 - 7

5 - 5
7 - 7
3 - 3
4 - 4
6 - 6