add LRU cache to PersistentMap

This should speed up fetching and inserting of values
that are used often.
This commit is contained in:
2019-02-02 17:26:07 +01:00
parent d4d1685f9f
commit 2e48061793

View File

@@ -124,6 +124,8 @@ public class PersistentMap<K, V> implements AutoCloseable {
private final LRUCache<Long, PersistentMapDiskNode> nodeCache = new LRUCache<>(10_000);
private final LRUCache<K, V> valueCache = new LRUCache<>(1_000);
public PersistentMap(final Path path, final EncoderDecoder<K> keyEncoder, final EncoderDecoder<V> valueEncoder)
throws IOException {
this.diskStore = new DiskStorage(path);
@@ -171,16 +173,32 @@ public class PersistentMap<K, V> 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 {