Which Java collection should I use to implement a thread-safe cache?

后端 未结 5 1618
后悔当初
后悔当初 2021-02-20 14:58

I\'m looking to implement a simple cache without doing too much work (naturally). It seems to me that one of the standard Java collections ought to suffice, with a little extra

5条回答
  •  囚心锁ツ
    2021-02-20 15:51

    LinkedHashMap is easy to use for cache. This creates an MRU cache of size 10.

    private LinkedHashMap cache = new LinkedHashMap(10, 0.7f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > 10;
        }
    };
    

    I guess you can make a class with synchronized delegates to this LinkedHashMap. Forgive me if my understanding of synchronization is wrong.

提交回复
热议问题