A builder of {@link Cache} instances having any combination of the following features:
- least-recently-used eviction when a maximum size is exceeded
- time-based expiration of entries, measured since last access or last write
- keys automatically wrapped in {@linkplain WeakReference weak} references
- values automatically wrapped in {@linkplain WeakReference weak} or{@linkplain SoftReference soft} references
- notification of evicted (or otherwise removed) entries
Usage example:
{@code Cache graphs = CacheBuilder.newBuilder() .concurrencyLevel(4) .weakKeys() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(}new CacheLoader() public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });}
These features are all optional.
The returned cache is implemented as a hash table with similar performance characteristics to {@link ConcurrentHashMap}. It implements the optional operations {@link Cache#invalidate}, {@link Cache#invalidateAll}, {@link Cache#size}, {@link Cache#stats}, and {@link Cache#asMap}, with the following qualifications:
- The {@code invalidateAll} method will invalidate all cached entries prior to returning, andremoval notifications will be issued for all invalidated entries.
- The {@code asMap} view supports removal operations, but no other modifications.
- The {@code asMap} view (and its collection views) have weakly consistent iterators.This means that they are safe for concurrent use, but if other threads modify the cache after the iterator is created, it is undefined which of these changes, if any, are reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}.
Note: by default, the returned cache uses equality comparisons (the {@link Object#equals equals} method) to determine equality for keys or values. However, if{@link #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys. Likewise, if {@link #weakValues} or {@link #softValues} wasspecified, the cache uses identity comparisons for values.
If soft or weak references were requested, it is possible for a key or value present in the the cache to be reclaimed by the garbage collector. If this happens, the entry automatically disappears from the cache. A partially-reclaimed entry is never exposed to the user.
The caches produced by {@code CacheBuilder} are serializable, and the deserialized cachesretain all the configuration properties of the original cache.
@param < K> the base key type for all caches created by this builder
@param < V> the base value type for all caches created by this builder
@author Charles Fry
@author Kevin Bourrillion
@since Guava release 10