Gep
Gep

Reputation: 928

Guava CacheBuilder prevent load for specific values

I have the following java code to build a Guava cache:

myCache = CacheBuilder.newBuilder()
            .build(new CacheLoader<Result, String>() {
                       @Override
                       public Result load(String s) throws Exception {
                          Result result = getResult(s);

                          // if (result == Result.INVALID) return ???

                          return result;
                       }
                   }
            );

I would like to add some code whereby if the result is a specific value then nothing is loaded into the cache. Not sure how to do it. Any suggestions? Many thanks!

Upvotes: 1

Views: 491

Answers (1)

Grzegorz Rożniecki
Grzegorz Rożniecki

Reputation: 28055

Simple answer: just throw an exception. See CacheLoader docs:

Returns:
  the value associated with key; must not be null
Throws:
  Exception - if unable to load the result

In your case it would be something like:

    myCache = CacheBuilder.newBuilder()
        .build(new CacheLoader<Result, String>() {
                   @Override
                   public Result load(String s) throws Exception {
                      Result result = getResult(s);
                      if (result == Result.INVALID) {
                          throw new InvalidResultException();
                      }
                      return result;
                   }
               }
        );

and you should use get(K) or getUnchecked(K) to handle the exception accordingly, see Guava wiki about caches.

Please note that in Caffeine, a Guava cache successor, you can return null from a CacheLoader#load(K) to indicate the value was not loaded:

Returns:
the value associated with key or null if not found
Throws:
Exception - or Error, in which case the mapping is unchanged

For more info, see Caffeine wiki about cache population.

Upvotes: 1

Related Questions