I have a service that using Caffeine Cache to store another class and I use the 'id' field in this class as the key.
Here's a simple example:
class MyService {
Cache<Long, MyObj> cache = Caffeine.newBuilder().build();
public void doSomething(long id) {
MyObj myObj = cache.get(id, k -> new MyObj(id));
}
}
class MyObj {
long id;
// other fields below...
public MyObj(long id) {
log.info("init complete. id {}", id);
}
}
My understanding of cache.get is that if the key does not exist, it will execute the function provided as the second parameter and store its result back into the cache. So, when I retrieve the value for the key for the first time, it will instantiate MyObj and display the log "init complete. id = 1" (assuming the id is 1) on the console.
But strangely, my console displays "init complete" three times at different time points.
Dec 19, 2023 @ 00:01:00.665 2023-12-19 00:01:00.664 INFO 11 --- [io-8080-exec-10] c.i.l.c.service.MyService : init complete. id = 63326
Dec 19, 2023 @ 00:00:49.833 2023-12-19 00:00:49.832 INFO 14 --- [io-8080-exec-10] c.i.l.c.service.MyService : init complete. id = 63326
Dec 19, 2023 @ 00:00:37.266 2023-12-19 00:00:37.266 INFO 14 --- [nio-8080-exec-7] c.i.l.c.service.MyService : init complete. id = 63326
I would like to understand why this situation is occurring.
Thank you.