Top Description Inners Fields Constructors Methods
com.google.common.cache

public final Class CacheBuilder<K, V>

extends Object
Class Inheritance
Annotations
@GwtCompatible
emulated:true
@ElementTypesAreNonnullByDefault
Type Parameters
<K>
the most general key type this builder will be able to create caches for. This is normally Object unless it is constrained by using a method like #removalListener. Cache keys may not be null.
<V>
the most general value type this builder will be able to create caches for. This is normally Object unless it is constrained by using a method like #removalListener. Cache values may not be null.
Static Imports
com.google.common.base.Preconditions.checkArgument, .Preconditions.checkNotNull, .Preconditions.checkState

A builder of LoadingCache and Cache instances.

Prefer Caffeine over Guava's caching API

The successor to Guava's caching API is Caffeine. Its API is designed to make it a nearly drop-in replacement -- though it requires Java 8 APIs, is not available for Android or GWT/j2cl, and may have different (usually better) behavior when multiple threads attempt concurrent mutations. Its equivalent to CacheBuilder is its Caffeine class. Caffeine offers better performance, more features (including asynchronous loading), and fewer bugs.

Caffeine defines its own interfaces (Cache, LoadingCache, CacheLoader, etc.), so you can use Caffeine without needing to use any Guava types. Caffeine's types are better than Guava's, especially for their deep support for asynchronous operations. But if you want to migrate to Caffeine with minimal code changes, you can use its CaffeinatedGuava adapter class, which lets you build a Guava Cache or a Guava LoadingCache backed by a Guava CacheLoader.

Caffeine's API for asynchronous operations uses CompletableFuture: AsyncLoadingCache.get returns a CompletableFuture, and implementations of AsyncCacheLoader.asyncLoad must return a CompletableFuture. Users of Guava's com.google.common.util.concurrent.ListenableFuture can adapt between the two Future types by using net.javacrumbs.futureconverter.java8guava.FutureConverter.

More on CacheBuilder

CacheBuilder builds caches with any combination of the following features:

These features are all optional; caches can be created using all or none of them. By default, cache instances created by CacheBuilder will not perform any type of eviction.

Usage example:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
    .maximumSize(10000)
    .expireAfterWrite(Duration.ofMinutes(10))
    .removalListener(MY_LISTENER)
    .build(
        new CacheLoader<Key, Graph>() {
          public Graph load(Key key) throws AnyException {
            return createExpensiveGraph(key);
          }
        });

Or equivalently,

// In real life this would come from a command-line flag or config file
String spec = "maximumSize=10000,expireAfterWrite=10m";

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 implements all optional operations of the LoadingCache and Cache interfaces. The 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 ConcurrentModificationException.

Note

by default, the returned cache uses equality comparisons (the equals method) to determine equality for keys or values. However, if weakKeys was specified, the cache uses identity (==) comparisons instead for keys. Likewise, if weakValues or softValues was 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 by Cache#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 in Cache#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#cleanUp method 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 CacheBuilder are 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.

Authors
Charles Fry, Kevin Bourrillion
Since
10.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
pack-priv static enum
pack-priv static enum

Field Summary

Modifier and TypeField and Description
pack-priv static final Supplier<AbstractCache.StatsCounter>
pack-priv int
private static final int
private static final int
private static final int
private static final int
pack-priv static final CacheStats
pack-priv long
pack-priv long
pack-priv int
pack-priv Equivalence<Object>
pack-priv LocalCache.Strength
pack-priv long
pack-priv long
pack-priv static final Supplier<? extends AbstractCache.StatsCounter>
pack-priv static final Ticker
pack-priv long
pack-priv RemovalListener<? super K, ? super V>
pack-priv Supplier<? extends AbstractCache.StatsCounter>
pack-priv boolean
pack-priv Ticker
pack-priv static final int
pack-priv Equivalence<Object>
pack-priv LocalCache.Strength
pack-priv Weigher<? super K, ? super V>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public <K1 extends K, V1 extends V> LoadingCache<K1, V1>

Returns:

a cache having the requested features
build
(CacheLoader<? super K1, V1>
the cache loader used to obtain new values
loader
)

Builds a cache, which either returns an already-loaded value for a given key or atomically computes or retrieves it using the supplied CacheLoader.

public <K1 extends K, V1 extends V> Cache<K1, V1>

Returns:

a cache having the requested features
build
()

Builds a cache which does not automatically load values when keys are requested.

private void
private void
public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
concurrencyLevel
(int concurrencyLevel)

Guides the allowed concurrency among update operations.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
expireAfterAccess
(Duration
the length of time after an entry is last accessed that it should be automatically removed
duration
)

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.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
expireAfterAccess
(long
the length of time after an entry is last accessed that it should be automatically removed
duration
,
TimeUnit
the unit that duration is expressed in
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.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
expireAfterWrite
(Duration
the length of time after an entry is created that it should be automatically removed
duration
)

Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
expireAfterWrite
(long
the length of time after an entry is created that it should be automatically removed
duration
,
TimeUnit
the unit that duration is expressed in
unit
)

Specifies that each entry should be automatically removed from the cache once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

public static CacheBuilder<Object, Object>
from(CacheBuilderSpec spec)

Constructs a new CacheBuilder instance with the settings specified in spec.

public static CacheBuilder<Object, Object>
from(String
a String in the format specified by CacheBuilderSpec
spec
)

Constructs a new CacheBuilder instance with the settings specified in spec.

pack-priv int
pack-priv long
pack-priv long
pack-priv int
pack-priv Equivalence<Object>
pack-priv LocalCache.Strength
pack-priv long
pack-priv long
pack-priv <K1 extends K, V1 extends V> RemovalListener<K1, V1>
pack-priv Supplier<? extends AbstractCache.StatsCounter>
pack-priv Ticker
getTicker(boolean recordsTime)

pack-priv Equivalence<Object>
pack-priv LocalCache.Strength
pack-priv <K1 extends K, V1 extends V> Weigher<K1, V1>
public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
initialCapacity
(int initialCapacity)

Sets the minimum total size for the internal hash tables.

pack-priv boolean
pack-priv CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
keyEquivalence
(Equivalence<Object> equivalence)

Sets a custom Equivalence strategy for comparing keys.

pack-priv CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
lenientParsing
()

Enables lenient parsing.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
maximumSize
(long
the maximum size of the cache
maximumSize
)

Specifies the maximum number of entries the cache may contain.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
maximumWeight
(long
the maximum total weight of entries the cache may contain
maximumWeight
)

Specifies the maximum weight of entries the cache may contain.

public static CacheBuilder<Object, Object>
newBuilder()

Constructs a new CacheBuilder instance with default settings, including strong keys, strong values, and no automatic eviction of any kind.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
recordStats
()

Enable the accumulation of CacheStats during the operation of the cache.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
refreshAfterWrite
(Duration
the length of time after an entry is created that it should be considered stale, and thus eligible for refresh
duration
)

Specifies that active entries are eligible for automatic refresh once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
refreshAfterWrite
(long
the length of time after an entry is created that it should be considered stale, and thus eligible for refresh
duration
,
TimeUnit
the unit that duration is expressed in
unit
)

Specifies that active entries are eligible for automatic refresh once a fixed duration has elapsed after the entry's creation, or the most recent replacement of its value.

public <K1 extends K, V1 extends V> CacheBuilder<K1, V1>

Returns:

the cache builder reference that should be used instead of this for any remaining configuration and cache building
removalListener
(RemovalListener<? super K1, ? super V1> listener)

Specifies a listener instance that caches should notify each time an entry is removed for any reason.

pack-priv CacheBuilder<K, V>
pack-priv CacheBuilder<K, V>
public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
softValues
()

Specifies that each value (not key) stored in the cache should be wrapped in a SoftReference (by default, strong references are used).

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
ticker
(Ticker ticker)

Specifies a nanosecond-precision time source for this cache.

private static long
toNanosSaturated(Duration duration)

Returns the number of nanoseconds of the given duration without throwing or overflowing.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation for this CacheBuilder instance.
pack-priv CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
valueEquivalence
(Equivalence<Object> equivalence)

Sets a custom Equivalence strategy for comparing values.

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
weakKeys
()

Specifies that each key (not value) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

public CacheBuilder<K, V>

Returns:

this CacheBuilder instance (for chaining)
weakValues
()

Specifies that each value (not key) stored in the cache should be wrapped in a WeakReference (by default, strong references are used).

public <K1 extends K, V1 extends V> CacheBuilder<K1, V1>

Returns:

this CacheBuilder instance (for chaining)
weigher
(Weigher<? super K1, ? super V1>
the weigher to use in calculating the weight of cache entries
weigher
)

Specifies the weigher to use in determining the weight of entries.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait