我正在使用咖啡因缓存。
我想把它放在大小限制之下,但它不能正常工作。
测试1:
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(3)
.build();
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(3)
.build();
for (int i = 1; i <= 10; i ++) {
String val = String.valueOf(i);
cache.put(val, val);
}
System.out.println("cache size: " + cache.estimatedSize() + ", cache keys: " + cache.asMap().values().stream().collect(Collectors.joining(",")));
result: cache size: 10, cache keys: 1,2,10
另一个测试:尝试获取密钥并将最大值设置为 1
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(1)
.build();
for (int i = 1; i <= 10; i ++) {
String val = String.valueOf(i);
cache.put(val, val);
if (i % 2 == 0) {
cache.getIfPresent("5");
}
}
System.out.println("cache size: " + cache.estimatedSize() + ", cache keys: " + cache.asMap().values().stream().collect(Collectors.joining(",")));
cache size: 10, cache keys: 2,3,4,5,6,7,8,9,10
最后一次测试:运行 100 次,最大尺寸 1
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(1)
.build();
for (int i = 1; i <= 100; i ++) {
String val = String.valueOf(i);
cache.put(val, val);
if (i % 2 == 0) {
cache.getIfPresent("5");
}
}
System.out.println("cache size: " + cache.estimatedSize() + ", cache keys: " + cache.asMap().values().stream().collect(Collectors.joining(",")));
cache size: 99, cache keys: 96,97,99,19,23,58
有人可以帮我理解这一点以及如何使其正常工作吗?
感谢 Ben Manes,我补充说.executor(Runnable::run)
现在这样做之后,我只得到 3 件物品
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(3)
.executor(Runnable::run)
.build();
for (int i = 1; i <= 10; i ++) {
String val = String.valueOf(i);
cache.put(val, val);
if (i % 2 == 0) {
cache.getIfPresent("5");
}
}
cache.cleanUp();
System.out.println("cache size: " + cache.estimatedSize() + ", cache: " + CodecUtils.toJson(cache.asMap().values()));
cache size: 3, cache: ["3","9","10"]
- 这不会阻止我的线程吗?
- 为什么我已经多次使用它的缓存中没有键 5?