add LRU cache to PersistentMap
This should speed up fetching and inserting of values that are used often.
This commit is contained in:
@@ -124,6 +124,8 @@ public class PersistentMap<K, V> implements AutoCloseable {
|
|||||||
|
|
||||||
private final LRUCache<Long, PersistentMapDiskNode> nodeCache = new LRUCache<>(10_000);
|
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)
|
public PersistentMap(final Path path, final EncoderDecoder<K> keyEncoder, final EncoderDecoder<V> valueEncoder)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
this.diskStore = new DiskStorage(path);
|
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 {
|
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[] encodedKey = keyEncoder.encode(key);
|
||||||
final byte[] encodedValue = valueEncoder.encode(value);
|
final byte[] encodedValue = valueEncoder.encode(value);
|
||||||
final byte[] oldValue = putValue(encodedKey, encodedValue);
|
final byte[] encodedOldValue = putValue(encodedKey, encodedValue);
|
||||||
return oldValue == null ? null : valueEncoder.decode(oldValue);
|
final V oldValue = encodedOldValue == null ? null : valueEncoder.decode(encodedOldValue);
|
||||||
|
valueCache.put(key, value);
|
||||||
|
return oldValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized V getValue(final K key) throws IOException {
|
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[] encodedKey = keyEncoder.encode(key);
|
||||||
final byte[] foundValue = getValue(encodedKey);
|
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 {
|
private byte[] putValue(final byte[] key, final byte[] value) throws IOException {
|
||||||
|
|||||||
Reference in New Issue
Block a user