Java SE API

Bounded cache retention

Apply a count-based eviction policy in a single-threaded example.

Formal Syntax & Structure

java syntaxjava
removeEldestEntry(eldest)

Working Example

Example Snippetjava
public class Main {    static class Cache extends java.util.LinkedHashMap<String,Integer> {        private static final long serialVersionUID = 1L;        Cache() { super(4, 0.75f, true); }        @Override protected boolean removeEldestEntry(java.util.Map.Entry<String,Integer> eldest) { return size() > 2; }    }    public static void main(String[] args) throws Exception {        var cache = new Cache();        cache.put("A", 1); cache.put("B", 2);        cache.get("A"); cache.put("C", 3);        System.out.println(cache.keySet());        System.out.println(cache.size());    }}
Java Reference