Skip to content

Commit

Permalink
fix: use concurrent hashmap instead of synchroniztion for recordcache
Browse files Browse the repository at this point in the history
Signed-off-by: Lev Povolotsky <[email protected]>
  • Loading branch information
povolev15 committed Jan 23, 2024
1 parent 12c2ff0 commit fd3fb3d
Showing 1 changed file with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
* A base class for implementations of {@link ReadableKVState} and {@link WritableKVState}.
Expand All @@ -38,10 +40,12 @@ public abstract class ReadableKVStateBase<K, V> implements ReadableKVState<K, V>
* changed before we got to handle transaction. If the value is "null", this means it was NOT
* FOUND when we looked it up.
*/
private final Map<K, V> readCache = Collections.synchronizedMap(new HashMap<>());
private final ConcurrentMap<K, V> readCache = new ConcurrentHashMap<>();

private final Set<K> unmodifiableReadKeys = Collections.unmodifiableSet(readCache.keySet());

private static final Object marker = new Object();

/**
* Create a new StateBase.
*
Expand Down Expand Up @@ -69,7 +73,8 @@ public V get(@NonNull K key) {
final var value = readFromDataSource(key);
markRead(key, value);
}
return readCache.get(key);
final var value = readCache.get(key);
return (value == marker) ? null : value;
}

/**
Expand Down Expand Up @@ -121,7 +126,9 @@ public void reset() {
* @param value The value
*/
protected final void markRead(@NonNull K key, @Nullable V value) {
readCache.put(key, value);
if (value == null) readCache.put(key, (V)marker);
else readCache.put(key, value);

}

/**
Expand All @@ -131,6 +138,7 @@ protected final void markRead(@NonNull K key, @Nullable V value) {
* @return Whether it has been read
*/
protected final boolean hasBeenRead(@NonNull K key) {
return readCache.containsKey(key);
var keyExistence = readCache.get(key);
return keyExistence != null && keyExistence != marker;
}
}

0 comments on commit fd3fb3d

Please sign in to comment.