From 2e4806179343a95be1a939fc319ef51382331759 Mon Sep 17 00:00:00 2001 From: Andreas Huber Date: Sat, 2 Feb 2019 17:26:07 +0100 Subject: [PATCH] add LRU cache to PersistentMap This should speed up fetching and inserting of values that are used often. --- .../org/lucares/pdb/map/PersistentMap.java | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/block-storage/src/main/java/org/lucares/pdb/map/PersistentMap.java b/block-storage/src/main/java/org/lucares/pdb/map/PersistentMap.java index 69dc042..4686cee 100644 --- a/block-storage/src/main/java/org/lucares/pdb/map/PersistentMap.java +++ b/block-storage/src/main/java/org/lucares/pdb/map/PersistentMap.java @@ -124,6 +124,8 @@ public class PersistentMap implements AutoCloseable { private final LRUCache nodeCache = new LRUCache<>(10_000); + private final LRUCache valueCache = new LRUCache<>(1_000); + public PersistentMap(final Path path, final EncoderDecoder keyEncoder, final EncoderDecoder valueEncoder) throws IOException { this.diskStore = new DiskStorage(path); @@ -171,16 +173,32 @@ public class PersistentMap implements AutoCloseable { } public synchronized V putValue(final K key, final V value) throws IOException { + + final V cachedValue = valueCache.get(key); + if (cachedValue != null && cachedValue == value) { + return value; + } + final byte[] encodedKey = keyEncoder.encode(key); final byte[] encodedValue = valueEncoder.encode(value); - final byte[] oldValue = putValue(encodedKey, encodedValue); - return oldValue == null ? null : valueEncoder.decode(oldValue); + final byte[] encodedOldValue = putValue(encodedKey, encodedValue); + final V oldValue = encodedOldValue == null ? null : valueEncoder.decode(encodedOldValue); + valueCache.put(key, value); + return oldValue; } public synchronized V getValue(final K key) throws IOException { + + final V cachedValue = valueCache.get(key); + if (cachedValue != null) { + return cachedValue; + } + final byte[] encodedKey = keyEncoder.encode(key); final byte[] foundValue = getValue(encodedKey); - return foundValue == null ? null : valueEncoder.decode(foundValue); + final V result = foundValue == null ? null : valueEncoder.decode(foundValue); + valueCache.put(key, result); + return result; } private byte[] putValue(final byte[] key, final byte[] value) throws IOException {