Class CacheBuilder<K,V>
- java.lang.Object
-
- org.glassfish.jersey.internal.guava.CacheBuilder<K,V>
-
- Type Parameters:
K- the base key type for all caches created by this builderV- the base value type for all caches created by this builder
public final class CacheBuilder<K,V> extends Object
A builder of
LoadingCacheandCacheinstances having any combination of the following features:- automatic loading of entries into the cache
- 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 weak references
- values automatically wrapped in weak or soft references
- notification of evicted (or otherwise removed) entries
- accumulation of cache access statistics
These features are all optional; caches can be created using all or none of them. By default cache instances created by
CacheBuilderwill not perform any type of eviction.Usage example:
<p> LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .removalListener(MY_LISTENER) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });Or equivalently,
<p> // In real life this would come from a command-line flag or config file String spec = "maximumSize=10000,expireAfterWrite=10m"; <p> LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec) .removalListener(MY_LISTENER) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });The returned cache is implemented as a hash table with similar performance characteristics to
ConcurrentHashMap. It implements all optional operations of theLoadingCacheandCacheinterfaces. TheasMapview (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 throwConcurrentModificationException.Note: by default, the returned cache uses equality comparisons (the
equalsmethod) to determine equality for keys or values. However, if#weakKeyswas specified, the cache uses identity (==) comparisons instead for keys. Likewise, if#weakValuesor#softValueswas specified, the cache uses identity comparisons for values.Entries are automatically evicted from the cache when any of maximumSize, maximumWeight, expireAfterWrite, expireAfterAccess, weakKeys, weakValues, or softValues are requested.
If maximumSize or maximumWeight is requested entries may be evicted on each cache modification.
If expireAfterWrite or expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to
Cache#cleanUp. Expired entries may be counted byCache#size, but will never be visible to read or write operations.If weakKeys, weakValues, or softValues are requested, it is possible for a key or value present in the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on each cache modification, on occasional cache accesses, or on calls to
Cache#cleanUp; such entries may be counted inCache#size, but will never be visible to read or write operations.Certain cache configurations will result in the accrual of periodic maintenance tasks which will be performed during write operations, or during occasional read operations in the absence of writes. The
Cache#cleanUpmethod of the returned cache will also perform maintenance, but calling it should not be necessary with a high throughput cache. Only caches built with removalListener, expireAfterWrite, expireAfterAccess, weakKeys, weakValues, or softValues perform periodic maintenance.The caches produced by
CacheBuilderare serializable, and the deserialized caches retain all the configuration properties of the original cache. Note that the serialized form does not include cache contents, but only configuration.See the Guava User Guide article on caching for a higher-level explanation.
- Since:
- 10.0
- Author:
- Charles Fry, Kevin Bourrillion
-
-
Field Summary
Fields Modifier and Type Field Description static TickerNULL_TICKER
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description <K1 extends K,V1 extends V>
Cache<K1,V1>build()Builds a cache which does not automatically load values when keys are requested.<K1 extends K,V1 extends V>
LoadingCache<K1,V1>build(CacheLoader<? super K1,V1> loader)Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the suppliedCacheLoader.CacheBuilder<K,V>expireAfterAccess(long duration, TimeUnit unit)Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access.CacheBuilder<K,V>maximumSize(long size)Specifies the maximum number of entries the cache may contain.static CacheBuilder<Object,Object>newBuilder()Constructs a newCacheBuilderinstance with default settings, including strong keys, strong values, and no automatic eviction of any kind.StringtoString()Returns a string representation for this CacheBuilder instance.
-
-
-
Field Detail
-
NULL_TICKER
public static final Ticker NULL_TICKER
-
-
Method Detail
-
newBuilder
public static CacheBuilder<Object,Object> newBuilder()
Constructs a newCacheBuilderinstance with default settings, including strong keys, strong values, and no automatic eviction of any kind.
-
maximumSize
public CacheBuilder<K,V> maximumSize(long size)
Specifies the maximum number of entries the cache may contain. Note that the cache may evict an entry before this limit is exceeded. As the cache size grows close to the maximum, the cache evicts entries that are less likely to be used again. For example, the cache may evict an entry because it hasn't been used recently or very often.When
sizeis zero, elements will be evicted immediately after being loaded into the cache. This can be useful in testing, or to disable caching temporarily without a code change.This feature cannot be used in conjunction with
maximumWeight.- Parameters:
size- the maximum size of the cache- Throws:
IllegalArgumentException- ifsizeis negativeIllegalStateException- if a maximum size or weight was already set
-
expireAfterAccess
public CacheBuilder<K,V> expireAfterAccess(long duration, TimeUnit unit)
Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, the most recent replacement of its value, or its last access. Access time is reset by all cache read and write operations (includingCache.asMap().get(Object)andCache.asMap().put(K, V)), but not by operations on the collection-views ofCache#asMap.When
durationis zero, this method hands off tomaximumSize(0), ignoring any otherwise-specificed maximum size or weight. This can be useful in testing, or to disable caching temporarily without a code change.Expired entries may be counted in
Cache#size, but will never be visible to read or write operations. Expired entries are cleaned up as part of the routine maintenance described in the class javadoc.- Parameters:
duration- the length of time after an entry is last accessed that it should be automatically removedunit- the unit thatdurationis expressed in- Throws:
IllegalArgumentException- ifdurationis negativeIllegalStateException- if the time to idle or time to live was already set
-
build
public <K1 extends K,V1 extends V> LoadingCache<K1,V1> build(CacheLoader<? super K1,V1> loader)
Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the suppliedCacheLoader. If another thread is currently loading the value for this key, simply waits for that thread to finish and returns its loaded value. Note that multiple threads can concurrently load values for distinct keys.This method does not alter the state of this
CacheBuilderinstance, so it can be invoked again to create multiple independent caches.- Parameters:
loader- the cache loader used to obtain new values- Returns:
- a cache having the requested features
-
build
public <K1 extends K,V1 extends V> Cache<K1,V1> build()
Builds a cache which does not automatically load values when keys are requested.Consider
build(CacheLoader)instead, if it is feasible to implement aCacheLoader.This method does not alter the state of this
CacheBuilderinstance, so it can be invoked again to create multiple independent caches.- Returns:
- a cache having the requested features
- Since:
- 11.0
-
-