LinkedHashMap removeEldestEntry: How many elements are removed?

十年热恋 提交于 2019-12-11 03:35:51

问题


LinkedHashMap looks brilliant to implement LRU Cache. It has some overheads in terms of linked list management and not thread safe but then it simplifies the implementation and I can take care of these in my code.

The question I have, which I don't find answer so far about is how many elements LinkedHashMap removes from the list if removeEldestEntry is implemented and put finds the list full.

Does it remove just one element? or some percentage of the total size. My concern is if it removes just one element to put new element then its a real performance issue. As I see the rehash operations are very costly.

Please someone suggest how it works and If I can manage these to be removed elements count using InitialCapacity, LoadFactor or any other way.


回答1:


LinkedHashMap is good to implement the most trivial cache, but for more advanced requirements it's probably not ideal.

Returning true from removeEldestEntry will cause the single, eldest entry to be removed, there's no way to tweak this to multiple elements.

Maybe something like the Guava CacheBuilder might be what you're looking for.




回答2:


LinkedHashMap looks brilliant to implement LRU Cache. It has some overheads in terms of linked list management

This is true of all LRU caches.

and not thread safe

You can use Collections.synchronizedMap()

The question I have, which I don't find answer so far about is how many elements LinkedHashMap removes from the list if removeEldestEntry is implemented and put finds the list full.

It removes the eldest entry. I.e. one and only one.

From the source for LinkedHashMap

    if (removeEldestEntry(eldest)) {
        removeEntryForKey(eldest.key);

My concern is if it removes just one element to put new element then its a real performance issue.

It isn't.

As I see the rehash operations are very costly.

Rehashing only occurs when the capacity grows, not when an entry is removed.



来源:https://stackoverflow.com/questions/11669149/linkedhashmap-removeeldestentry-how-many-elements-are-removed

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