Skip to content

Commit

Permalink
fix[cache]: update expire time when put value
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysunxiao committed Mar 27, 2024
1 parent fda2d6a commit a28544d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public LazyCache(int maximumSize, long expireAfterAccessMillis, long expireCheck
public void put(K key, V value) {
var cacheValue = new CacheValue<V>();
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down Expand Up @@ -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<Integer, String>(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);
}
}

}

0 comments on commit a28544d

Please sign in to comment.