Guava Cache Guide: Building, Loading, Eviction, Refresh, and Advanced Features
This article explains how to create and configure Guava LoadingCache instances, covering builder options, CacheLoader implementation, explicit insertion, callable loading, size‑based, timed, and reference‑based eviction, removal listeners, refresh strategies, statistics, asMap view, and interruption handling, with complete Java code examples.
The article begins with a concrete example of constructing a LoadingCache<Key, Graph> using CacheBuilder.newBuilder() , setting a maximum size of 1000 entries, an expiration after write of 10 minutes, and attaching a removal listener before calling .build() with a custom CacheLoader that implements Graph load(Key key) to create expensive graph objects.
It then discusses the applicability of Guava Cache, noting that it is suitable when you can afford extra memory for speed, expect keys to be queried multiple times, and the total cached data fits in memory, otherwise external solutions like Memcached may be preferable.
The LoadingCache section shows how to define a CacheLoader<Key, Graph> by overriding public Graph load(Key key) throws AnyException , and how to retrieve values with graphs.get(key) (which may throw ExecutionException ) or graphs.getUnchecked(key) when the loader does not declare checked exceptions.
For manual loading, the article presents the Cache.get(K, Callable<V>) method, demonstrating a cache without a loader and using a Callable to compute and insert a value atomically.
Explicit insertion is covered with cache.put(key, value) and the caveats of using the asMap() view, which does not guarantee atomic loading.
Eviction strategies are detailed: Size‑based eviction via CacheBuilder.maximumSize(long) or weighted eviction with maximumWeight and a custom Weigher . Timed eviction using expireAfterAccess or expireAfterWrite , and how to test it with a custom Ticker . Reference‑based eviction with weakKeys() , weakValues() , and softValues() .
Removal listeners can be registered with CacheBuilder.removalListener(RemovalListener) to perform cleanup actions when entries are evicted; the listener receives a RemovalNotification containing the key, value, and cause.
Refresh functionality is explained via LoadingCache.refresh(K) and the builder option refreshAfterWrite . An asynchronous reload example shows overriding CacheLoader.reload(K, V) to return a ListenableFuture that computes the new value without blocking reads.
Additional features include enabling statistics with CacheBuilder.recordStats() to obtain hit rate, load penalty, and eviction count, and using the asMap() view for concurrent map operations while noting its impact on access timestamps.
The article concludes with a discussion on interruption handling: LoadingCache does not throw InterruptedException directly, but if a user‑provided CacheLoader is interruptible, the exception is wrapped in ExecutionException . It explains why Guava chooses this design and mentions the potential for an AsyncLoadingCache to provide proper interrupt semantics.
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.