I am using caffeine cache.
I want to put it under size limitation but it does not work properly.
test 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
another test: trying to get key and set max to 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
last test : run 100 times, max size 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
can someone please help me understand this and how to make it work properly?
Thanks to Ben Manes, I added .executor(Runnable::run)
Now after doing this I do get only 3 items
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"]
- wouldn't this block my thread?
- why isn't key 5 in the cache as I have been using it several times?