From 7f09cac0aa1451ef0e0c330f908cc279df323e17 Mon Sep 17 00:00:00 2001 From: nea Date: Mon, 19 Dec 2022 23:10:16 +0100 Subject: LRUCache: Cache null results --- .../io/github/moulberry/notenoughupdates/util/LRUCache.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/io/github/moulberry/notenoughupdates/util/LRUCache.java b/src/main/java/io/github/moulberry/notenoughupdates/util/LRUCache.java index f107d522..6adbc30d 100644 --- a/src/main/java/io/github/moulberry/notenoughupdates/util/LRUCache.java +++ b/src/main/java/io/github/moulberry/notenoughupdates/util/LRUCache.java @@ -32,13 +32,15 @@ public interface LRUCache extends Function { } static LRUCache memoize(Function mapper, IntSupplier maxCacheSize) { - Map cache = new LinkedHashMap(10, 0.75F, true) { + Map cache = new LinkedHashMap(10, 0.75F, true) { @Override - protected boolean removeEldestEntry(Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { return this.size() > maxCacheSize.getAsInt(); } }; - Map synchronizedCache = Collections.synchronizedMap(cache); + Object SENTINEL_CACHE_RESULT_NULL = new Object(); + Function sentinelAwareMapper = mapper.andThen(it -> it == null ? SENTINEL_CACHE_RESULT_NULL : it); + Map synchronizedCache = Collections.synchronizedMap(cache); return new LRUCache() { @Override public void clearCache() { @@ -52,7 +54,8 @@ public interface LRUCache extends Function { @Override public V apply(K k) { - return synchronizedCache.computeIfAbsent(k, mapper); + Object value = synchronizedCache.computeIfAbsent(k, sentinelAwareMapper); + return value == SENTINEL_CACHE_RESULT_NULL ? null : (V) value; } }; } -- cgit