This commit is contained in:
Looly
2021-10-19 00:27:10 +08:00
parent f966fda28f
commit 3e36d7fd21
9 changed files with 337 additions and 135 deletions

View File

@@ -0,0 +1,52 @@
package cn.hutool.cache;
import cn.hutool.cache.impl.LRUCache;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
/**
* 见https://github.com/dromara/hutool/issues/1895<br>
* 并发问题测试在5.7.15前LRUCache存在并发问题多线程get后map结构变更导致null的位置不确定
* 并可能引起死锁。
*/
public class LRUCacheTest {
@Test
public void readWriteTest() throws InterruptedException {
LRUCache<Integer, Integer> cache = CacheUtil.newLRUCache(10);
for (int i = 0; i < 10; i++) {
cache.put(i, i);
}
CountDownLatch countDownLatch = new CountDownLatch(10);
// 10个线程分别读0-9 10000次
for (int i = 0; i < 10; i++) {
int finalI = i;
new Thread(() -> {
for (int j = 0; j < 10000; j++) {
cache.get(finalI);
}
countDownLatch.countDown();
}).start();
}
// 等待读线程结束
countDownLatch.await();
// 按顺序读0-9
StringBuilder sb1 = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb1.append(cache.get(i));
}
Assert.assertEquals("0123456789", sb1.toString());
// 新加11此时0最久未使用应该淘汰0
cache.put(11, 11);
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb2.append(cache.get(i));
}
Assert.assertEquals("null123456789", sb2.toString());
}
}