Frequently Used metadata Hashmap

穿精又带淫゛_ 提交于 2019-12-08 03:04:25

问题


Are there any implementations of a static size hashtable that limits the entries to either the most recently or most frequently used metadata? I would prefer not to keep track of this information myself.

I know most caching components keep track of this, but I would rather not introduce quite a lot of new dependencies.


回答1:


You can build an LRU cache using the standard JDK library using LinkedHashMap:

public class MyLRUCache<K, V> extends LinkedHashMap<K, V> {

    private final int maxEntries;

    public MyLRUCache(int maxEntries) {
        // you can be a bit fancy with capacity and load factor
        super(16, 0.75, true);
        this.maxEntries = maxEntries;
    }

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

You may want to play with WeakReferences as well.




回答2:


Use LinkedHashMap and override removeEldestEntry and make sure to use the constructor that allows to accessOrder as true

Accessordered makes the map remove the least recently accessed item instead of the eldest.

All queries will alter the structure of the map, hence be a tiny bit slower.

Example:

public AccesOrderedLRUCache<V,K> extends LinkedHashMap<V,K>{
    private final m_capacity;

    public AccesOrderedLRUCache(int capacity) {
        super(0.75*capacity, 0.75, true);
        m_capacity = capacity;
    }

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

    public int getCapacity() {
        return m_capacity;
    }
}


来源:https://stackoverflow.com/questions/1689127/frequently-used-metadata-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!