Files

lru-cache

Runnable companion for the ankurm.com article LRU Cache in Java: LinkedHashMap, HashMap + Doubly Linked List and a Thread-Safe Version.

Three LRU caches, three thread-safe variants, a Caffeine reference, a deliberately broken ReadWriteLock version, correctness and stress tests, and a short JMH comparison.

Component Version Verified against
JDK 25.0.5+8 (Temurin, LTS) java -version
JUnit 6.1.3 maven-metadata.xml on Maven Central
Caffeine 3.3.1 maven-metadata.xml; GitHub release page lists it as Latest
JMH 1.37 maven-metadata.xml
export JAVA_HOME=/path/to/jdk-25 && export PATH="$JAVA_HOME/bin:$PATH"
cd lru-cache
mvn test                 # 43 tests; rewrites output/01-08
./scripts/run-all.sh     # also regenerates output/09 (broken-lock demo) and 10 (JMH)
Source What it is
LinkedHashMapLruCache LinkedHashMap(accessOrder=true) + removeEldestEntry
HashMapLruCache HashMap + hand-rolled doubly linked list with sentinel head/tail
SynchronizedLruCache, ReentrantLockLruCache one coarse lock around variant 2
StripedLruCache N independent segments, LRU per segment (not global)
BrokenReadWriteLockLruCache, BrokenLockDemo the tempting wrong answer, and what it does
CaffeineLru, bench/LruBenchmark production reference and the JMH harness

output/09 and output/10 are measurements from a shared 2-vCPU sandbox: indicative, not asserted.