diff --git a/src/main/java/cc/ryanc/halo/cache/InMemoryCacheStore.java b/src/main/java/cc/ryanc/halo/cache/InMemoryCacheStore.java index 5f5019d9a..0ad8bf1d4 100644 --- a/src/main/java/cc/ryanc/halo/cache/InMemoryCacheStore.java +++ b/src/main/java/cc/ryanc/halo/cache/InMemoryCacheStore.java @@ -5,6 +5,8 @@ import org.springframework.util.Assert; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** * In-memory cache store. @@ -19,6 +21,11 @@ public class InMemoryCacheStore extends StringCacheStore { */ private final static ConcurrentHashMap> cacheContainer = new ConcurrentHashMap<>(); + /** + * Lock. + */ + private Lock lock = new ReentrantLock(); + @Override Optional> getInternal(String key) { Assert.hasText(key, "Cache key must not be blank"); @@ -38,26 +45,29 @@ public class InMemoryCacheStore extends StringCacheStore { } @Override - synchronized Boolean putInternalIfAbsent(String key, CacheWrapper cacheWrapper) { + Boolean putInternalIfAbsent(String key, CacheWrapper cacheWrapper) { Assert.hasText(key, "Cache key must not be blank"); Assert.notNull(cacheWrapper, "Cache wrapper must not be null"); log.debug("Preparing to put key: [{}], value: [{}]", key, cacheWrapper); - // Get the value before - Optional valueOptional = get(key); + try { + lock.lock(); + // Get the value before + Optional valueOptional = get(key); - if (valueOptional.isPresent()) { - log.warn("Failed to put the cache, because the key: [{}] has been present already", key); - return false; + if (valueOptional.isPresent()) { + log.warn("Failed to put the cache, because the key: [{}] has been present already", key); + return false; + } + + // Put the cache wrapper + putInternal(key, cacheWrapper); + log.debug("Put successfully"); + return true; + } finally { + lock.unlock(); } - - // Put the cache wrapper - putInternal(key, cacheWrapper); - - log.debug("Put successfully"); - - return true; } @Override