How to implement a most-recently-used cache

后端 未结 4 984
孤独总比滥情好
孤独总比滥情好 2020-12-09 04:40

What would be the best way to implement a most-recently-used cache of objects?

Here are the requirements and restrictions...

  • Objects are stored as key/
4条回答
  •  情话喂你
    2020-12-09 05:20

    Why implement something already implemented? Use Ehcache.

    However, if third-party libraries are totally out of the question, I guess you are looking to implement a data structure which looks something like this:

    • Basically is a HashMap (extends HashMap if you will)
    • Each value in the Map points to an object in a sorted list, based on which is most used.
    • Objects recently used are added to the head of the list - O(1)
    • Purging least-recently used means truncating the end of the list - O(1)
    • Still gives you Map lookups, but still keeps recently-used items first...

提交回复
热议问题