diff --git a/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java b/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java index 58a78d573..155956b3b 100644 --- a/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java +++ b/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java @@ -80,7 +80,7 @@ public LazyCache(int maximumSize, long expireAfterAccessMillis, long expireCheck public void put(K key, V value) { var cacheValue = new CacheValue(); cacheValue.value = value; - cacheValue.expireTime = TimeUtils.now(); + cacheValue.expireTime = TimeUtils.now() + expireAfterAccessMillis; var oldCacheValue = cacheMap.put(key, cacheValue); if (oldCacheValue != null) { removeListener.accept(new Pair<>(key, oldCacheValue.value), RemovalCause.REPLACED); diff --git a/scheduler/src/test/java/com/zfoo/scheduler/util/LazyCacheTest.java b/scheduler/src/test/java/com/zfoo/scheduler/util/LazyCacheTest.java index fb2b5e86b..6c14895ad 100644 --- a/scheduler/src/test/java/com/zfoo/scheduler/util/LazyCacheTest.java +++ b/scheduler/src/test/java/com/zfoo/scheduler/util/LazyCacheTest.java @@ -102,7 +102,7 @@ public void batchTest() { @Test - public void multipleThreadTest() { + public void multiple1ThreadTest() { int threadNum = Runtime.getRuntime().availableProcessors() + 1; ExecutorService[] executors = new ExecutorService[threadNum]; for (int i = 0; i < executors.length; i++) { @@ -133,4 +133,36 @@ public void run() { } } + @Test + public void multiple2ThreadTest() { + int threadNum = Runtime.getRuntime().availableProcessors() + 1; + ExecutorService[] executors = new ExecutorService[threadNum]; + for (int i = 0; i < executors.length; i++) { + executors[i] = Executors.newSingleThreadExecutor(); + } + var lazyCache = new LazyCache(1_0000, 1000 * TimeUtils.MILLIS_PER_SECOND, 5 * TimeUtils.MILLIS_PER_SECOND, myRemoveCallback); + for (int i = 0; i < executors.length; i++) { + + var executor = executors[i]; + int i1 = i; + executor.execute(new Runnable() { + @Override + public void run() { + var startIndex = i1 * 1_0000; + for (int j = i1 * 1_0000; j < startIndex + 1_0000; j++) { + lazyCache.put(j, String.valueOf(j)); + } + for (int j = 0; j < 10000; j++) { + lazyCache.get(j); + ThreadUtils.sleep(1); + } + } + }); + } + for (int i = 0; i < 10000; i++) { + logger.info("cache size:[{}]", lazyCache.size()); + ThreadUtils.sleep(1000); + } + } + }