Reputation: 151
I am building an Least Recently Used Cache using a TreeMap in Java. The reason I selected the TreeMap is because of the TreeMap.floorEntry (String) method. I want to be able to specify a maximum size for my cache(TreeMap). Then I want to use an LRU eviction mechanism, and therefore, When the cache has reached the maximum size AND when there is a new record to be cached, I want the cache to add the new record, and remove the eldest entry.
Upvotes: 2
Views: 3569
Reputation: 1406
I hope I understood your problem correctly. I would use ConcurrentSkipListMap(which has also floorEntry method) and implement my own little max size control.
This is what I would do:
int maxSize = 100;
ConcurrentSkipListMap<String, String> cache = new ConcurrentSkipListMap<>();
// Check if max size is reached before inserting something in it. Make some room for new entry.
while (cache.size() >= maxSize) {
cache.pollFirstEntry();
}
It's a bit hackish but should do the job.
Upvotes: 1