From 83297a1d1010bda05e97aa9d7a7f34f56f41cfad Mon Sep 17 00:00:00 2001 From: Harrison Date: Thu, 30 Apr 2020 00:20:32 -0500 Subject: [PATCH] Improved cache performance by removing locks. These sync locks can be removed because of fixing the multithread cases in the previous commit. --- .../islandsurvivalcraft/caching/Cache.java | 31 ++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java b/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java index 1d24638..13586ea 100644 --- a/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java +++ b/src/main/java/ca/recrown/islandsurvivalcraft/caching/Cache.java @@ -1,17 +1,13 @@ package ca.recrown.islandsurvivalcraft.caching; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; -import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; +import java.util.concurrent.locks.ReentrantLock; public class Cache { private final int maxSize; private final ConcurrentHashMap> data; private final CacheUsageStack usage = new CacheUsageStack<>(); - private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - private final WriteLock writeLock = lock.writeLock(); - private final ReadLock readLock = lock.readLock(); + private final ReentrantLock lock = new ReentrantLock(); public Cache(int maxSize) { data = new ConcurrentHashMap<>(maxSize + 1, 0.75f, 16); @@ -33,7 +29,7 @@ public class Cache { if (data.containsKey(key)) { data.get(key).value = value; } else { - writeLock.lock(); + lock.lock(); try { CacheValue val = new CacheValue<>(); val.key = key; @@ -44,7 +40,7 @@ public class Cache { data.remove(usage.pop().key); } } finally { - writeLock.unlock(); + lock.unlock(); } } } @@ -57,29 +53,22 @@ public class Cache { * @return the value associated to the key. */ public V get(K key) { - CacheValue value = null; - value = data.get(key); - if (value == null) return null; - if (readLock.tryLock()) { - try { - usage.tryMoveToTop(value); - } finally { - readLock.unlock(); - } - } - return value.value; + CacheValue cacheValue = data.get(key); + if (cacheValue == null) return null; + usage.tryMoveToTop(cacheValue); + return cacheValue.value; } /** * Clears the cache of all values. */ public void clearCache() { - writeLock.lock(); + lock.lock(); try { data.clear(); usage.clear(); } finally { - writeLock.unlock(); + lock.unlock(); } } } \ No newline at end of file