Purpose of Caffeine's builder function argument?

hotmeatballsoup :

New to Caffeine and I'm clearly missing something super fundamental. All the basic usage examples I see look like this:

LoadingCache<String,Fizzbuzz> fizzbuzzes = Caffeine.newBuilder()
    .maximumSize(100)
    .expireAfterWrite(10, TimeUnit.DAYS)
    .build(k -> fetchFizzbuzzes());

What I'm struggling with is the role that the fetchFizzbuzzes() function plays:

  • Is it used to populate the initial cache?
  • Is it used as some sort of fallback in case a key doesn't exist in the cache?
  • Something else?
dpr :

Actually this is the most important part of the builder. The function passed to the build(CacheLoader) method takes a key and computes the value for this key. This function is called if there is currently no value for this key in the cache. The computed value will be added to the cache afterwards. There is a build() method without arguments as well, which can be used if you want to manually check for elements to be present in the cache and add them manually as well.

Your example however doesn't make too much sense as the fetchFizzbuzzes() method has no arguments. That is - without side effects - it will probably return the same value for all keys k.

Take the examples below:

LoadingCache<String,Fizzbuzz> fizzbuzzes = Caffeine.newBuilder()
    .maximumSize(100)
    .expireAfterWrite(10, TimeUnit.DAYS)
    .build(key -> fetchFizzbuzzes(key));
fizzbuzzes.get("myKey"); // will automatically invoke fetchFizzbuzzes with 'myKey' as argument
fizzbuzzes.get("myKey"); // fetchFizzbuzzes won't be called as return value from previous call is added to the cache automatically


Cache<String, Fizzbuzz> fizzbuzzesManual = Caffeine.newBuilder()
     .maximumSize(100)
     .expireAfterWrite(10, TimeUnit.DAYS)
     .build();
fizzbuzzesManual.getIfPresent("myKey"); // will return null as no element for 'myKey' was added to the cache before

See the Caffeine wiki for additional details.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92758&siteId=1