skip to content

Explain the contract of removeEldestEntry: when it's invoked, what 'eldest' means, and what returning true does.

level: seniorimportance: should knowfreq 45%

answer

  1. Protected hook, override in a subclass
  2. Called after a new entry goes in
  3. eldest = head = oldest/LRU entry
  4. Return true → map removes it for you
  5. Mutated the map yourself? Then return false

basics

~20 s

removeEldestEntry is a hook LinkedHashMap calls after a new entry goes in through put, putAll or a similar method, passing the oldest entry in its list. If your override returns true, the map removes that entry; the default returns false.

solid answer

~50 s

`removeEldestEntry(Map.Entry<K,V> eldest)` is a protected hook LinkedHashMap invokes immediately after a new entry is added via put/putAll, and in the source also `putIfAbsent`, `merge` and the compute family, but not during the copy constructor, `clone` or deserialization. The 'eldest' it passes is the head of its internal linked list — in insertion-order mode that's the least recently inserted entry, in access-order mode the least recently accessed, and on a map that was empty it is the entry just added. The base class returns `false`, meaning the map never auto-evicts; you override it to return `true` when you want LinkedHashMap to remove that eldest entry for you, one entry per call. It is normally a *decision* method: the Javadoc permits modifying the map inside it, but then it must return false. The eldest entry is provided so you can inspect its key/value (e.g., to log eviction or veto removal of pinned entries).

go deeper

for a junior

Knows removeEldestEntry decides whether to drop the oldest entry and that returning true causes eviction.

for a middle

States that it runs after a new entry goes in, that eldest is the head, and that you normally return a boolean and let the map do the removal.

for a senior

Explains the one-removal-per-true limit, the must-return-false rule when the override modifies the map, the evict flag, inspecting eldest for pinning/logging, and how mode changes what 'eldest' means.

for a principal

Articulates the policy-vs-mechanism separation behind the boolean design and the implications for custom eviction policies and invariants when extending LinkedHashMap.

## The method ```java protected boolean removeEldestEntry(Map.Entry<K,V> eldest) ``` It lives on `LinkedHashMap`. It is `protected`, so the intended use is to **subclass** LinkedHashMap and **override** it. ## When it is invoked The Javadoc says it "is invoked by `put` and `putAll` after inserting a new entry". The source goes a little further: the call sits in the internal `afterNodeInsertion` callback, which runs **once per new entry** after `put`, `putIfAbsent`, `merge` or `compute*` *adds* a node, and for each new entry of `putAll`. It is **not** called by `get`, `remove`, iteration, or a `put` that only replaces an existing key's value. That callback first checks an `evict` flag, and three paths insert with it `false`: the copy constructor, `clone` and deserialization. They make no call at all. A subclass capped at two entries holds three after the copy constructor and two after `putAll`, from the same source map. ## What 'eldest' means The argument is the **head** of the map's internal doubly-linked list — the 'oldest' entry by the map's current ordering: - **insertion-order mode (default):** the entry inserted earliest that still remains. - **access-order mode:** the **least-recently-used** entry (because accesses move entries to the tail). So the same hook builds a FIFO eviction cache in default mode or an LRU cache in access-order mode. Two edge cases follow from "head": - On a map that was empty before the insert, the eldest is the entry just inserted. An override that always returns `true` leaves the map empty after every `put`. - Since Java 21, `putFirst` links a new entry at the head before the hook runs, so a capped map can evict what it just added: capped at two, `put(1, 1)`, `put(2, 2)`, `putFirst(3, 3)` held `{1=1, 2=2}`. ## What the return value does - Return **`false`** → keep everything; nothing is removed. This is the **default** implementation, which is why a plain LinkedHashMap never shrinks on its own. - Return **`true`** → LinkedHashMap **removes the eldest entry** that was passed in. You do *not* remove it yourself. ## Contract / do's and don'ts - **Do** base your decision on `size()` (e.g., `return size() > capacity;`) and/or on inspecting `eldest.getKey()/getValue()` (e.g., never evict a 'pinned' entry). - **Modifying the map yourself** is the unusual path, and it has a rule. The Javadoc says the method "typically does not modify the map in any way", that it *is* permitted to, and that if it does, it *must* return `false`. "The effects of returning true after modifying the map from within this method are unspecified." So remove-and-return-false is legal, and it is a way to trim below the bound from inside the hook: an override that removes the eldest entries through an iterator takes a map from five entries to two in one `put`. - **Side effects** like logging an eviction or releasing a resource tied to `eldest` are fine. - Returning `true` removes **one** entry. Each new entry of a bulk insert gets its own hook call, so `putAll` trims incrementally. ## Why the design is shaped this way Making it a boolean *decision* function (rather than a 'doRemove' that you must implement) keeps the removal logic — unlinking from the list and the bucket, updating size and modCount — inside the map. In the usual case your job is only the *policy* (whether to evict), not the *mechanism*.

  • Can removeEldestEntry evict more than one entry in a single put?
    Not through its return value: true removes only the eldest. The override can remove more itself, which the Javadoc permits as long as it then returns false; an override can trim five entries to two in one put. Otherwise putAll trims one per new entry.
  • Is it correct to call map.remove(eldest.getKey()) inside the override?
    Only if the override then returns false: the Javadoc permits modifying the map there on that condition, and an override keeps its bound that way. Returning true after modifying has unspecified effects, so the simple form is to return true and leave the removal to the map.

  • Removing the entry inside the override and still returning true, whose effects are unspecified.
  • Believing the hook fires on get or remove — it only fires after a new entry goes in.
  • Assuming that returning true removes more than the one eldest entry.
  • Forgetting that 'eldest' depends on mode (insertion vs access order).
  • Expecting the copy constructor or clone to trim a capped subclass to its limit.

LinkedHashMap.removeEldestEntry
Java 1.4

Assumes JDK 27; LinkedHashMap.java is byte-identical at JDK 25. The hook dates from the class's arrival in 1.4; the putFirst case needs Java 21.

context