Top Description Inners Fields Constructors Methods
com.github.benmanes.caffeine.cache

public final Class Caffeine<K, V>

extends Object
Class Inheritance
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
<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
Static Imports
java.util.Locale.US, .Objects.requireNonNull

A builder of Cache, LoadingCache, AsyncCache, and AsyncLoadingCache instances having a 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 Caffeine will not perform any type of eviction.

Usage example:

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
      .maximumSize(10_000)
      .expireAfterWrite(Duration.ofMinutes(10))
      .removalListener((Key key, Graph graph, RemovalCause cause) ->
          System.out.printf("Key %s was removed (%s)%n", key, cause))
      .build(key -> createExpensiveGraph(key));

The returned cache is implemented as a hash table with similar performance characteristics to ConcurrentHashMap. 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, expireAfter, expireAfterWrite, expireAfterAccess, weakKeys, weakValues, or softValues are requested.

If maximumSize or maximumWeight is requested, entries may be evicted on each cache modification.

If expireAfter, expireAfterWrite, or expireAfterAccess is requested, then entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache#cleanUp. A scheduler(Scheduler) may be specified to provide prompt removal of expired entries rather than waiting until activity triggers the periodic maintenance. Expired entries may be counted by Cache#estimatedSize(), 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#estimatedSize(), but will never be visible to read or write operations.

Certain cache configurations will result in the accrual of periodic maintenance tasks that 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 maximumSize, maximumWeight, expireAfter, expireAfterWrite, expireAfterAccess, weakKeys, weakValues, or softValues perform periodic maintenance.

The caches produced by Caffeine 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.

Author
[email protected] (Ben Manes)

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static enum

Field Summary

Modifier and TypeField and Description
pack-priv static final int
pack-priv static final int
pack-priv static final double
pack-priv static final int
pack-priv static final Supplier<StatsCounter>
pack-priv @Nullable RemovalListener<? super K, ? super V>
pack-priv @Nullable Executor
pack-priv long
pack-priv long
pack-priv @Nullable Expiry<? super K, ? super V>
pack-priv int
pack-priv boolean
pack-priv @Nullable Caffeine.Strength
pack-priv static final System.Logger
pack-priv long
pack-priv long
pack-priv long
pack-priv @Nullable RemovalListener<? super K, ? super V>
pack-priv @Nullable Scheduler
pack-priv @Nullable Supplier<StatsCounter>
pack-priv boolean
pack-priv @Nullable Ticker
pack-priv static final int
pack-priv @Nullable Caffeine.Strength
pack-priv @Nullable Weigher<? super K, ? super V>

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public <
the key type of the cache
K1 extends K
,
the value type of the cache
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 unless a mapping function is provided.

public <
the key type of the loader
K1 extends K
,
the value type of the loader
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 <
the key type of the cache
K1 extends K
,
the value type of the cache
V1 extends V
>
AsyncCache<K1, V1>

Returns:

a cache having the requested features
buildAsync
()

Builds a cache which does not automatically load values when keys are requested unless a mapping function is provided.

public <
the key type of the loader
K1 extends K
,
the value type of the loader
V1 extends V
>
AsyncLoadingCache<K1, V1>

Returns:

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

Builds a cache, which either returns a CompletableFuture already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the supplied CacheLoader.

public <
the key type of the loader
K1 extends K
,
the value type of the loader
V1 extends V
>
AsyncLoadingCache<K1, V1>

Returns:

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

Builds a cache, which either returns a CompletableFuture already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the supplied AsyncCacheLoader.

pack-priv static int

Returns:

initial capacity for HashMap based classes
calculateHashMapCapacity
(int
the expected number of mappings
numMappings
)

Calculate initial capacity for HashMap-based classes, from expected size and default load factor (0.75).

pack-priv static int

Returns:

initial capacity for HashMap based classes
calculateHashMapCapacity
(Iterable<?>
the expected number of mappings
iterable
)

Calculate initial capacity for HashMap-based classes, from expected size and default load factor (0.75).

pack-priv static int
ceilingPowerOfTwo(int x)

Returns the smallest power of two greater than or equal to x.

pack-priv static long
ceilingPowerOfTwo(long x)

Returns the smallest power of two greater than or equal to x.

public <
the key type of the listener
K1 extends K
,
the value type of the listener
V1 extends V
>
Caffeine<K1, V1>

Returns:

the cache builder reference that should be used instead of this for any remaining configuration and cache building
evictionListener
(RemovalListener<? super K1, ? super V1>
a listener instance that caches should notify each time an entry is being automatically removed due to eviction
evictionListener
)

Specifies a listener instance that caches should notify each time an entry is evicted.

pack-priv boolean
public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
executor
(Executor
the executor to use for asynchronous execution
executor
)

Specifies the executor to use when running asynchronous tasks.

public <
key type of the expiry
K1 extends K
,
value type of the expiry
V1 extends V
>
Caffeine<K1, V1>

Returns:

this Caffeine instance (for chaining)
expireAfter
(Expiry<? super K1, ? super V1>
the expiry to use in calculating the expiration time of cache entries
expiry
)

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

public Caffeine<K, V>

Returns:

this Caffeine 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 Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
expireAfterAccess
(@NonNegative 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 read.

public Caffeine<K, V>

Returns:

this Caffeine 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 Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
expireAfterWrite
(@NonNegative 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.

pack-priv boolean
pack-priv boolean
pack-priv boolean
public static Caffeine<Object, Object>

Returns:

a new instance with the specification's settings
from
(CaffeineSpec
the specification to build from
spec
)

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

public static Caffeine<Object, Object>

Returns:

a new instance with the specification's settings
from
(String
a String in the format specified by CaffeineSpec
spec
)

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

pack-priv <K1 extends K, V1 extends V> @Nullable RemovalListener<K1, V1>
getEvictionListener(boolean async)

pack-priv Executor
pack-priv long
pack-priv long
pack-priv @Nullable Expiry<K, V>
getExpiry(boolean isAsync)

pack-priv int
pack-priv long
pack-priv long
pack-priv <K1 extends K, V1 extends V> @Nullable RemovalListener<K1, V1>
getRemovalListener(boolean async)

pack-priv Scheduler
pack-priv Supplier<StatsCounter>
pack-priv Ticker
pack-priv <K1 extends K, V1 extends V> Weigher<K1, V1>
getWeigher(boolean isAsync)

pack-priv boolean
public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
initialCapacity
(@NonNegative int
minimum total size for the internal data structures
initialCapacity
)

Sets the minimum total size for the internal data structures.

pack-priv boolean
pack-priv boolean
pack-priv boolean
pack-priv boolean
pack-priv boolean
pack-priv boolean
public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
maximumSize
(@NonNegative long
the maximum size of the cache
maximumSize
)

Specifies the maximum number of entries the cache may contain.

public Caffeine<K, V>

Returns:

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

Specifies the maximum weight of entries the cache may contain.

public static Caffeine<Object, Object>

Returns:

a new instance with default settings
newBuilder
()

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

pack-priv static <K> BoundedLocalCache<K, Boolean>
newWeakInterner()

Returns a cache that is optimized for weak reference interning (see Interner).

public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
recordStats
()

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

public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
recordStats
(Supplier<? extends StatsCounter>
a supplier instance that returns a new StatsCounter
statsCounterSupplier
)

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

public Caffeine<K, V>

Returns:

this Caffeine 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 Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
refreshAfterWrite
(@NonNegative 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.

pack-priv boolean
public <
the key type of the listener
K1 extends K
,
the value type of the listener
V1 extends V
>
Caffeine<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>
a listener instance that caches should notify each time an entry is removed
removalListener
)

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

pack-priv static void
requireArgument(boolean expression, String template, @Nullable Object... args)

Ensures that the argument expression is true.

pack-priv static void
requireArgument(boolean expression)

Ensures that the argument expression is true.

pack-priv void
pack-priv static void
requireState(boolean expression)

Ensures that the state expression is true.

pack-priv static void
requireState(boolean expression, String template, @Nullable Object... args)

Ensures that the state expression is true.

pack-priv void
pack-priv static long
saturatedToNanos(Duration duration)

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

public Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
scheduler
(Scheduler
the scheduler that submits a task to the executor(Executor) after a given delay
scheduler
)

Specifies the scheduler to use when scheduling routine maintenance based on an expiration event.

public Caffeine<K, V>

Returns:

this Caffeine 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 Caffeine<K, V>

Returns:

this Caffeine instance (for chaining)
ticker
(Ticker
a nanosecond-precision time source
ticker
)

Specifies a nanosecond-precision time source for use in determining when entries should be expired or refreshed.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation for this Caffeine instance.
public Caffeine<K, V>

Returns:

this Caffeine 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 Caffeine<K, V>

Returns:

this Caffeine 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 <
key type of the weigher
K1 extends K
,
value type of the weigher
V1 extends V
>
Caffeine<K1, V1>

Returns:

the cache builder reference that should be used instead of this for any remaining configuration and cache building
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