Skip to content

Commit 9ac62fc

Browse files
committed
How a normal LinkedHashMap vs a LinkedHashMap with accessOrder = true + removeEldestEntry()` (LRU Cache) behaves.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent f103162 commit 9ac62fc

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
How a normal LinkedHashMap vs a LinkedHashMap with accessOrder = true + removeEldestEntry()` (LRU Cache) behaves.
2+
3+
4+
5+
Case 1: Normal LinkedHashMap (Insertion Order):
6+
7+
Capacity doesn’t matter here since it doesn’t evict automatically.
8+
9+
Start: (empty)
10+
11+
put(A) → [A]
12+
put(B) → [A → B]
13+
put(C) → [A → B → C]
14+
15+
get(A) → [A → B → C] // No reordering
16+
put(D) → [A → B → C → D] // Just keeps growing
17+
18+
Insertion order is preserved. No eviction.
19+
20+
21+
22+
Case 2: LinkedHashMap with accessOrder = true (LRU Mode)
23+
24+
Assume capacity = 3 and removeEldestEntry() removes oldest when size > 3.
25+
26+
Start: (empty)
27+
28+
put(A) → [A]
29+
put(B) → [A → B]
30+
put(C) → [A → B → C]
31+
32+
get(A) → [B → C → A] // A moved to end (most recently used)
33+
34+
put(D) → capacity exceeded!
35+
→ Evict B (least recently used)
36+
→ [C → A → D]
37+
38+
get(C) → [A → D → C] // C moved to end
39+
40+
put(E) → capacity exceeded!
41+
→ Evict A
42+
→ [D → C → E]
43+
44+
45+
46+
Observations
47+
• Normal LinkedHashMap:
48+
49+
Just keeps keys in the order they were inserted, forever.
50+
• LinkedHashMap (LRU mode):
51+
• Every get() or put() moves the key to the end.
52+
• Once size > capacity, the eldest entry (front of the list) is evicted.
53+
• Ensures that only the most recently used items are kept.
54+
55+
56+
57+
That’s why LinkedHashMap(accessOrder=true) + removeEldestEntry() = ready-made LRU Cache implementation.
58+
59+

0 commit comments

Comments
 (0)