Question about LRU cache implementation in Java

A standard Java LRU Cache implementation example in Java points to an example depot URL http://www.exampledepot.com/egs/java.util/coll_Cache.html

How is removeEldestEntry called by default after adding a new entry to the code snippet below?

final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
    // This method is called just after a new entry has been added
    public boolean removeEldestEntry(Map.Entry eldest) {
        return size() > MAX_ENTRIES;
    }
};

// Add to cache
Object key = "key";
cache.put(key, object);

// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
    // Object not in cache. If null is not a possible value in the cache,
    // the call to cache.contains(key) is not needed
}

// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
+3
source share
3 answers

This example LinkedHashMapextends the anonymous inner class .

The method removeEldestEntryoverrides the version of the superclass that always returns false(indicating that the oldest record should not be deleted). The upper version returns trueif the card size exceeds the limit, indicating that the oldest record should be deleted.

+1

API Java LinkedHashMap:

removeEldestEntry(Map.Entry) , .

:

put putAll .

:

- , . , , false ( , ). .

+2

The documentation for the LinkedHashMap class says that it will call the removeEldestEntry () method at the appropriate time. In the above code, we provide an anonymous “extends” the LinkedHashMap class, which explicitly provides our implementation for this method.

0
source

Source: https://habr.com/ru/post/1714341/


All Articles