diff --git a/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java b/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java index 9dbc073..31f3354 100644 --- a/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java +++ b/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java @@ -2,19 +2,22 @@ package ca.recrown.islandsurvivalcraft.caching; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.locks.ReentrantLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; +import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; public class Cache { private final int maxSize; private final ConcurrentHashMap> data; private final ConcurrentLinkedQueue occurrenceOrder; - private ReentrantLock cleaningLock; + private ReentrantReadWriteLock cleaningLock = new ReentrantReadWriteLock(true); + private ReadLock writeLock = cleaningLock.readLock(); + private WriteLock readLock = cleaningLock.writeLock(); public Cache(int maxSize) { - data = new ConcurrentHashMap<>(maxSize); + data = new ConcurrentHashMap<>(maxSize + 1, 0.75f, 6); occurrenceOrder = new ConcurrentLinkedQueue<>(); this.maxSize = maxSize; - cleaningLock = new ReentrantLock(true); } public Cache() { @@ -34,14 +37,14 @@ public class Cache { Key potentialKey = occurrenceOrder.poll(); CacheValue potential = data.get(potentialKey); potential.occurrence--; - cleaningLock.lock(); + writeLock.lock(); try { occ = potential.occurrence; if (occ < 1) { data.remove(potentialKey); } } finally { - cleaningLock.unlock(); + writeLock.unlock(); } } while (occ > 0); } @@ -56,16 +59,15 @@ public class Cache { */ public Value getValue(Key key) { CacheValue res = null; - cleaningLock.lock(); + readLock.lock(); try { res = data.get(key); if (res == null) return null; res.occurrence++; occurrenceOrder.add(key); } finally { - cleaningLock.unlock(); + readLock.unlock(); } - return res.data; }