Java – Guava cache : cacheloader vs get(k,callable)


I am new to Guava cache, I am confused after reading the document

Whats the difference between using a cacheloader with load method vs using a get method with callable get(K, Callable) to load the key if it doesn't exists in cache.

To me they both serve the same purpose of loading the key. Cant find the diff between two from thew doc.
can someone please help.

Best Solution

The main advantage of a LoadingCache is that it promotes performing the computation through the cache, rather than a racy get then compute then put approach that is often used instead. It communicates to developers how the cache should be used.

Feature wise a LoadingCache provides bulk loading (getAll), non-blocking refresh, and a little brevity such as getUnchecked. A refresh may be performed explicitly through refresh(key) or implicitly using refreshAfterWrite during the build phase.

When the computation is complex then its nice to move the logic into its own class. By extending a CacheLoader instead of a Callable it communicates the intent a little better.

Performance wise there isn't a big difference. The get(key, callable) internally creates a decorator CacheLoader on every invocation that adapts to a load, so there is an eden space object created.

In my Java 8 rewrite, Caffeine, there are some additional options. An AsyncLoadingCache provides a similar API but returns a CompletableFuture. If you require more direct control, the new Map compute methods are supported as atomic operations.

In general prefer to use a LoadingCache for its communicative properties to the rest of your team. Everything else is gravy.