java数据访问策略_java – 支持基于最近访问过的项目的高效启动策略的数据结构...
我需要一個(gè)數(shù)據(jù)結(jié)構(gòu),以支持最長(zhǎng)時(shí)間前請(qǐng)求的項(xiàng)目的最有效的啟動(dòng)策略.例如,我有一堆不時(shí)要求的物品.當(dāng)我內(nèi)存不足時(shí),我想踢出我數(shù)據(jù)結(jié)構(gòu)中最古老的項(xiàng)目(哈希映射).
我在想像Queue這樣的FIFO ds,但我不知道如何處理這種情況:
–> a b c d a –>
a是最古老和最新的項(xiàng)目.如果再次添加“a”,我需要搜索整個(gè)隊(duì)列來(lái)刪除它.這是非常低效的,但我想不出任何有效的方法.也許是某種樹(shù)形結(jié)構(gòu),將最少訪問(wèn)的樹(shù)結(jié)構(gòu)保持在頂部?
Java中是否有任何這種數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn)?
解決方法:
LinkedHashMap是您追求的結(jié)構(gòu).從the docs開(kāi)始:
A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.
Map map = new LinkedHashMap<>(CAPACITY, LOAD_FACTOR, true);
boolean參數(shù)確定映射是訪問(wèn)順序還是插入順序. true表示訪問(wèn)順序.
此外,如果您希望地圖作為L(zhǎng)RU緩存工作,您可以創(chuàng)建自己的類來(lái)擴(kuò)展LinkedHashMap并覆蓋removeEldestEntry方法.再次,從文檔:
The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
這意味著您可以為緩存創(chuàng)建自己的類:
public class Cache extends LinkedHashMap {
private static final int MAX_ENTRIES = 100;
public Cache() {
super(SOME_INITIAL_CAPACITY, SOME_LOAD_FACTOR, true);
}
protected boolean removeEldestEntry(Entry entry) {
return size() > MAX_ENTRIES;
}
}
用法:
Map map = new Cache<>();
標(biāo)簽:java,data-structures
來(lái)源: https://codeday.me/bug/20190827/1746084.html
總結(jié)
以上是生活随笔為你收集整理的java数据访问策略_java – 支持基于最近访问过的项目的高效启动策略的数据结构...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 21款宝来夏天第一次启动转速五百转感觉要
- 下一篇: 日产为什么叫尼桑车?