ReentrantReadWriteLock Memoizing Cache
Build a thread-safe memoizing cache where ReentrantReadWriteLock lets concurrent readers share access while writers take the exclusive side.
Code
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;
public class MemoizingCache<K, V> {
private final Map<K, V> store = new HashMap<>();
private final Function<K, V> loader;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public MemoizingCache(Function<K, V> loader) {
this.loader = loader;
}
public V get(K key) {
// 读锁共享:多读者并发命中
lock.readLock().lock();
try {
V known = store.get(key);
if (known != null) {
return known;
}
} finally {
lock.readLock().unlock();
}
// 写锁独占:只有一个加载者填充
lock.writeLock().lock();
try {
V known = store.get(key);
if (known != null) {
return known; // 双重检查:别的线程可能已填充
}
V loaded = loader.apply(key);
store.put(key, loaded);
return loaded;
} finally {
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
MemoizingCache<Integer, String> cache = new MemoizingCache<>(id -> "value-" + id);
System.out.println(cache.get(42));
System.out.println(cache.get(42));
}
}How it works
Count the class MemoizingCache and the functions MemoizingCache, get and main as the entire surface area of ReentrantReadWriteLock Memoizing Cache.
Using it
The main signature reads public MemoizingCache(Function<K, V> loader)
The entry point wires get together — run it once and the whole demo flows.
Key statements
return known; // 双重检查:别的线程可能已填充
}
Interactive Tools for This Topic
Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- How do you run ReentrantReadWriteLock Memoizing Cache?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.