What is access-order mode in LinkedHashMap and how do you enable it?
answer
- 3-arg constructor, accessOrder = true
- Access moves entry to the tail
- Head = LRU, tail = MRU
- get counts as access; containsKey does not
- get mutates → CME risk while iterating
basics
~20 sAccess-order mode makes LinkedHashMap move an entry to the end of its list each time a method such as get or put touches it, so the least-recently-accessed entries stay at the front. You turn it on with the three-argument constructor passing true.
solid answer
~50 sBy default LinkedHashMap orders entries by insertion. Pass `true` as the third constructor argument — `new LinkedHashMap<>(initialCapacity, loadFactor, true)` — to switch to access-order mode. Now any *access* of an entry moves it to the tail of the linked list. "Access" includes `get`, `getOrDefault`, and a `put`/`merge`/`compute` that touches an existing key; plain reads like `containsKey` or anything done through the collection views do **not** count. The result is that the head of the list is the least-recently-accessed entry and the tail the most-recently-accessed, unless the positioning methods of Java 21, such as `putFirst`, place an entry elsewhere. This is the foundation for an LRU cache: combine access-order with an overridden `removeEldestEntry` to evict the head when the map exceeds a size bound. One gotcha: the documentation calls `get` a structural modification in this mode, so a `get` during iteration, from any thread, can make the iterator throw `ConcurrentModificationException`.
code
java · 9 lines// accessOrder = true (third arg)
LinkedHashMap<String,Integer> m =
new LinkedHashMap<>(16, 0.75f, true);
m.put("a", 1);
m.put("b", 2);
m.put("c", 3);
m.get("a"); // access 'a' -> moves it to the tail
System.out.println(m); // {b=2, c=3, a=1} -- 'a' is now most-recently-used
// head 'b' is the least-recently-used entrygo deeper
Knows there is an access-order mode enabled by a constructor flag that reorders on use.
Can enable it correctly, lists exactly which operations count as an access, and identifies head=LRU / tail=MRU.
Explains the modCount/CME interaction, thread-safety limits, and connects access-order to LRU eviction design.
Weighs access-order LinkedHashMap against dedicated cache libraries such as Caffeine on concurrency, eviction policy flexibility, and observability before choosing it for a system.
## Background A **LinkedHashMap** is a HashMap that also keeps a **doubly-linked list** (each entry has `before`/`after` pointers) running through all entries; this list decides iteration order. By default the list is in **insertion order**. ## The third constructor argument LinkedHashMap has a constructor `LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)`. The boolean `accessOrder` is the switch: - `false` (the default, and what the simpler constructors use) → **insertion-order** mode. - `true` → **access-order** mode. ## What access-order does In access-order mode, every time an entry is **accessed**, LinkedHashMap unlinks it from its current spot and re-appends it at the **tail** of the list. "Accessed" means: - `get(key)` / `getOrDefault(key, ...)` that finds the key, - `put(key, value)` / `putIfAbsent` / `merge` / `compute*` that operates on an **existing** key, - `replace(...)`, only if the value is actually replaced, - `putAll`, which generates one access per mapping, in the order the source map's entry-set iterator yields them. The documentation adds "No other methods generate entry accesses". So it does **not** include `containsKey`, `containsValue`, `size`, or anything done through the `keySet`/`entrySet`/`values` views — those leave order alone. (Note `getOrDefault` *does* count as an access if the key is present.) Consequence: with these methods alone, the **head** (front) of the list is the entry accessed longest ago — the **least-recently-used (LRU)** — and the **tail** is the **most-recently-used (MRU)**. That ordering is exactly what an LRU cache needs. Since Java 21, explicit-positioning methods such as `putFirst` and `lastEntry` "do not generate entry accesses", and `putFirst` can move any entry to the head. ## Why this matters Access-order mode is the engine behind a bounded LRU cache: you keep the most-recently-used items near the tail and evict from the head. You typically pair it with overriding `removeEldestEntry` (covered in its own question) so the map auto-evicts the eldest (head) entry once it grows past a capacity limit. ## Pitfalls 1. **`get` mutates structure.** The documentation says that in this mode "merely querying the map with `get` is a structural modification". A `get` that moves an entry increments the map's internal `modCount`, so calling it while iterating the same map can trigger a `ConcurrentModificationException` even though you only "read". A `get` on the current tail moves nothing, and an iteration survives it, but do not rely on that. 2. **Not thread-safe.** Concurrent reads can race because reads now write. Wrap with `Collections.synchronizedMap` plus external synchronization on iteration, or use a dedicated concurrent cache library such as Caffeine instead. 3. **Views do not refresh recency.** A value changed through `Map.Entry.setValue` during iteration leaves the entry where it was, so it can be evicted while looking freshly written.
- Does calling containsKey reorder the list in access-order mode?No. The documented accesses are put, putIfAbsent, get, getOrDefault, compute, computeIfAbsent, computeIfPresent, merge, putAll, and a replace that replaces the value. containsKey, size, and the collection views leave order untouched.
- Why can a plain get throw ConcurrentModificationException in access-order mode?Because a get on any entry but the tail reorders the linked list, which bumps the map's modCount. If that happens during iteration, the iterator's fail-fast check can detect the modification and throw on its next step. It is best-effort: on the last pass no next step comes, and nothing is thrown.
Think of a stack of papers on a desk in access-order mode: every time you pick up and use a sheet, you put it back on top. The sheet at the very bottom is the one you haven't touched in the longest time — the first you'd throw away if the desk got too full.
- Saying you enable access order with a method call like setAccessOrder() — it is only settable via the constructor and is final thereafter.
- Claiming containsKey or iteration reorders entries — they do not.
- Thinking the head is the most-recently-used — it is the least-recently-used.
- Assuming access-order LinkedHashMap is safe to share across threads for reads.
- LinkedHashMap access-order mode
- Java 1.4
Assumes JDK 27; LinkedHashMap.java is byte-identical at JDK 25. Access order dates from the class's arrival in 1.4; the positioning methods that generate no access, such as putFirst, are since Java 21.
context
- LinkedHashMap (Java SE 27 & JDK 27)docs.oracle.com