Class Caffeine<K,V>
- Type Parameters:
K
- the most general key type this builder will be able to create caches for. This is normallyObject
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 normallyObject
unless it is constrained by using a method like#removalListener
Cache
, LoadingCache
, AsyncCache
, and
AsyncLoadingCache
instances having a combination of the following features:
- automatic loading of entries into the cache, optionally asynchronously
- size-based eviction when a maximum is exceeded based on frequency and recency
- time-based expiration of entries, measured since last access or last write
- asynchronously refresh when the first stale request for an entry occurs
- keys automatically wrapped in weak references
- values automatically wrapped in weak or soft references
- writes propagated to an external resource
- 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 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 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
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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static final class
(package private) static enum
-
Field Summary
FieldsModifier and TypeFieldDescription(package private) static final int
(package private) static final int
(package private) static final int
(package private) static final Supplier
<StatsCounter> (package private) @Nullable RemovalListener
<? super K, ? super V> (package private) @Nullable Executor
(package private) long
(package private) long
(package private) int
(package private) @Nullable Caffeine.Strength
(package private) static final Logger
(package private) long
(package private) long
(package private) long
(package private) @Nullable RemovalListener
<? super K, ? super V> (package private) @Nullable Scheduler
(package private) @Nullable Supplier
<StatsCounter> (package private) boolean
(package private) @Nullable Ticker
(package private) static final int
(package private) @Nullable Caffeine.Strength
(package private) @Nullable CacheWriter
<? super K, ? super V> -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbuild()
Builds a cache which does not automatically load values when keys are requested unless a mapping function is provided.<K1 extends K,
V1 extends V>
@NonNull LoadingCache<K1, V1> build
(@NonNull 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
.<K1 extends K,
V1 extends V>
@NonNull AsyncCache<K1, V1> Builds a cache which does not automatically load values when keys are requested unless a mapping function is provided.<K1 extends K,
V1 extends V>
@NonNull AsyncLoadingCache<K1, V1> buildAsync
(@NonNull AsyncCacheLoader<? super K1, V1> loader) Builds a cache, which either returns aCompletableFuture
already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the suppliedAsyncCacheLoader
.<K1 extends K,
V1 extends V>
@NonNull AsyncLoadingCache<K1, V1> buildAsync
(@NonNull CacheLoader<? super K1, V1> loader) Builds a cache, which either returns aCompletableFuture
already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the suppliedCacheLoader
.(package private) static int
ceilingPowerOfTwo
(int x) Returns the smallest power of two greater than or equal tox
.(package private) static long
ceilingPowerOfTwo
(long x) Returns the smallest power of two greater than or equal tox
.evictionListener
(@NonNull RemovalListener<? super K1, ? super V1> evictionListener) Specifies a listener instance that caches should notify each time an entry is evicted.(package private) boolean
evicts()
Specifies the executor to use when running asynchronous tasks.expireAfter
(@NonNull Expiry<? super K1, ? super V1> 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.expireAfterAccess
(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull 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 read.expireAfterAccess
(@NonNull Duration 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.expireAfterWrite
(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull TimeUnit 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.expireAfterWrite
(@NonNull Duration 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.(package private) boolean
(package private) boolean
(package private) boolean
from
(CaffeineSpec spec) Constructs a newCaffeine
instance with the settings specified inspec
.Constructs a newCaffeine
instance with the settings specified inspec
.(package private) <K1 extends K,
V1 extends V>
CacheWriter<K1, V1> getCacheWriter
(boolean async) (package private) @NonNull Executor
(package private) long
(package private) long
getExpiry
(boolean isAsync) (package private) int
(package private) long
(package private) long
(package private) <K1 extends K,
V1 extends V>
@Nullable RemovalListener<K1, V1> getRemovalListener
(boolean async) (package private) @NonNull Scheduler
(package private) @NonNull Supplier
<StatsCounter> (package private) @NonNull Ticker
getWeigher
(boolean isAsync) (package private) boolean
initialCapacity
(@org.checkerframework.checker.index.qual.NonNegative int initialCapacity) Sets the minimum total size for the internal data structures.(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
(package private) boolean
maximumSize
(@org.checkerframework.checker.index.qual.NonNegative long maximumSize) Specifies the maximum number of entries the cache may contain.maximumWeight
(@org.checkerframework.checker.index.qual.NonNegative long maximumWeight) Specifies the maximum weight of entries the cache may contain.Constructs a newCaffeine
instance with default settings, including strong keys, strong values, and no automatic eviction of any kind.Enables the accumulation ofCacheStats
during the operation of the cache.recordStats
(@NonNull Supplier<? extends StatsCounter> statsCounterSupplier) Enables the accumulation ofCacheStats
during the operation of the cache.(package private) boolean
refreshAfterWrite
(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull TimeUnit 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.refreshAfterWrite
(@NonNull Duration 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.removalListener
(@NonNull RemovalListener<? super K1, ? super V1> removalListener) Specifies a listener instance that caches should notify each time an entry is removed for any reason.(package private) static void
requireArgument
(boolean expression) Ensures that the argument expression is true.(package private) static void
requireArgument
(boolean expression, String template, @Nullable Object... args) Ensures that the argument expression is true.(package private) void
(package private) static void
requireState
(boolean expression) Ensures that the state expression is true.(package private) static void
requireState
(boolean expression, String template, @Nullable Object... args) Ensures that the state expression is true.(package private) void
private static long
saturatedToNanos
(Duration duration) Returns the number of nanoseconds of the given duration without throwing or overflowing.Specifies the scheduler to use when scheduling routine maintenance based on an expiration event.Specifies that each value (not key) stored in the cache should be wrapped in aSoftReference
(by default, strong references are used).Specifies a nanosecond-precision time source for use in determining when entries should be expired or refreshed.toString()
Returns a string representation for this Caffeine instance.weakKeys()
Specifies that each key (not value) stored in the cache should be wrapped in aWeakReference
(by default, strong references are used).Specifies that each value (not key) stored in the cache should be wrapped in aWeakReference
(by default, strong references are used).Specifies the weigher to use in determining the weight of entries.writer
(@NonNull CacheWriter<? super K1, ? super V1> writer) Deprecated.Scheduled for removal in version 3.0.0.
-
Field Details
-
logger
-
ENABLED_STATS_COUNTER_SUPPLIER
-
UNSET_INT
static final int UNSET_INT- See Also:
-
DEFAULT_INITIAL_CAPACITY
static final int DEFAULT_INITIAL_CAPACITY- See Also:
-
DEFAULT_EXPIRATION_NANOS
static final int DEFAULT_EXPIRATION_NANOS- See Also:
-
DEFAULT_REFRESH_NANOS
static final int DEFAULT_REFRESH_NANOS- See Also:
-
strictParsing
boolean strictParsing -
maximumSize
long maximumSize -
maximumWeight
long maximumWeight -
initialCapacity
int initialCapacity -
expireAfterWriteNanos
long expireAfterWriteNanos -
expireAfterAccessNanos
long expireAfterAccessNanos -
refreshAfterWriteNanos
long refreshAfterWriteNanos -
evictionListener
@Nullable RemovalListener<? super K,? super V> evictionListener -
removalListener
@Nullable RemovalListener<? super K,? super V> removalListener -
statsCounterSupplier
@Nullable Supplier<StatsCounter> statsCounterSupplier -
writer
@Nullable CacheWriter<? super K,? super V> writer -
weigher
-
expiry
-
scheduler
@Nullable Scheduler scheduler -
executor
@Nullable Executor executor -
ticker
@Nullable Ticker ticker -
keyStrength
@Nullable Caffeine.Strength keyStrength -
valueStrength
@Nullable Caffeine.Strength valueStrength
-
-
Constructor Details
-
Caffeine
private Caffeine()
-
-
Method Details
-
requireArgument
@FormatMethod static void requireArgument(boolean expression, String template, @Nullable Object... args) Ensures that the argument expression is true. -
requireArgument
static void requireArgument(boolean expression) Ensures that the argument expression is true. -
requireState
static void requireState(boolean expression) Ensures that the state expression is true. -
requireState
@FormatMethod static void requireState(boolean expression, String template, @Nullable Object... args) Ensures that the state expression is true. -
ceilingPowerOfTwo
static int ceilingPowerOfTwo(int x) Returns the smallest power of two greater than or equal tox
. -
ceilingPowerOfTwo
static long ceilingPowerOfTwo(long x) Returns the smallest power of two greater than or equal tox
. -
newBuilder
Constructs a newCaffeine
instance with default settings, including strong keys, strong values, and no automatic eviction of any kind.Note that while this return type is
Caffeine<Object, Object>
, type parameters on thebuild()
methods allow you to create a cache of any key and value type desired.- Returns:
- a new instance with default settings
-
from
Constructs a newCaffeine
instance with the settings specified inspec
.- Parameters:
spec
- the specification to build from- Returns:
- a new instance with the specification's settings
-
from
Constructs a newCaffeine
instance with the settings specified inspec
.- Parameters:
spec
- a String in the format specified byCaffeineSpec
- Returns:
- a new instance with the specification's settings
-
initialCapacity
public @NonNull Caffeine<K,V> initialCapacity(@org.checkerframework.checker.index.qual.NonNegative int initialCapacity) Sets the minimum total size for the internal data structures. Providing a large enough estimate at construction time avoids the need for expensive resizing operations later, but setting this value unnecessarily high wastes memory.- Parameters:
initialCapacity
- minimum total size for the internal data structures- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifinitialCapacity
is negativeIllegalStateException
- if an initial capacity was already set
-
hasInitialCapacity
boolean hasInitialCapacity() -
getInitialCapacity
int getInitialCapacity() -
executor
Specifies the executor to use when running asynchronous tasks. The executor is delegated to when sending removal notifications, when asynchronous computations are performed byAsyncCache
orLoadingCache.refresh(K)
orrefreshAfterWrite(java.time.Duration)
, or when performing periodic maintenance. By default,ForkJoinPool.commonPool()
is used.The primary intent of this method is to facilitate testing of caches which have been configured with
removalListener
or utilize asynchronous computations. A test may instead prefer to configure the cache to execute tasks directly on the same thread.Beware that configuring a cache with an executor that discards tasks or never runs them may experience non-deterministic behavior.
- Parameters:
executor
- the executor to use for asynchronous execution- Returns:
- this
Caffeine
instance (for chaining) - Throws:
NullPointerException
- if the specified executor is null
-
getExecutor
@NonNull Executor getExecutor() -
scheduler
Specifies the scheduler to use when scheduling routine maintenance based on an expiration event. This augments the periodic maintenance that occurs during normal cache operations to allow for the prompt removal of expired entries regardless of whether any cache activity is occurring at that time. By default,Scheduler.disabledScheduler()
is used.The scheduling between expiration events is paced to exploit batching and to minimize executions in short succession. This minimum difference between the scheduled executions is implementation-specific, currently at ~1 second (2^30 ns). In addition, the provided scheduler may not offer real-time guarantees (including
ScheduledThreadPoolExecutor
). The scheduling is best-effort and does not make any hard guarantees of when an expired entry will be removed.Note for Java 9 and later: consider using
Scheduler.systemScheduler()
to leverage the dedicated, system-wide scheduling thread.- Parameters:
scheduler
- the scheduler that submits a task to theexecutor(Executor)
after a given delay- Returns:
- this
Caffeine
instance (for chaining) - Throws:
NullPointerException
- if the specified scheduler is null
-
getScheduler
@NonNull Scheduler getScheduler() -
maximumSize
public @NonNull Caffeine<K,V> maximumSize(@org.checkerframework.checker.index.qual.NonNegative long maximumSize) Specifies the maximum number of entries the cache may contain. Note that the cache may evict an entry before this limit is exceeded or temporarily exceed the threshold while evicting. 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
size
is 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. As eviction is scheduled on the configuredexecutor
, tests may instead prefer to configure the cache to execute tasks directly on the same thread.This feature cannot be used in conjunction with
maximumWeight
.- Parameters:
maximumSize
- the maximum size of the cache- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifsize
is negativeIllegalStateException
- if a maximum size or weight was already set
-
maximumWeight
public @NonNull Caffeine<K,V> maximumWeight(@org.checkerframework.checker.index.qual.NonNegative long maximumWeight) Specifies the maximum weight of entries the cache may contain. Weight is determined using theWeigher
specified withweigher
, and use of this method requires a corresponding call toweigher
prior to callingbuild()
.Note that the cache may evict an entry before this limit is exceeded or temporarily exceed the threshold while evicting. 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
maximumWeight
is 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. As eviction is scheduled on the configuredexecutor
, tests may instead prefer to configure the cache to execute tasks directly on the same thread.Note that weight is only used to determine whether the cache is over capacity; it has no effect on selecting which entry should be evicted next.
This feature cannot be used in conjunction with
maximumSize
.- Parameters:
maximumWeight
- the maximum total weight of entries the cache may contain- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifmaximumWeight
is negativeIllegalStateException
- if a maximum weight or size was already set
-
weigher
public <K1 extends K,V1 extends V> @NonNull Caffeine<K1,V1> weigher(@NonNull Weigher<? super K1, ? super V1> weigher) Specifies the weigher to use in determining the weight of entries. Entry weight is taken into consideration bymaximumWeight(long)
when determining which entries to evict, and use of this method requires a corresponding call tomaximumWeight(long)
prior to callingbuild()
. Weights are measured and recorded when entries are inserted into or updated in the cache, and are thus effectively static during the lifetime of a cache entry.When the weight of an entry is zero it will not be considered for size-based eviction (though it still may be evicted by other means).
Important note: Instead of returning this as a
Caffeine
instance, this method returnsCaffeine<K1, V1>
. From this point on, either the original reference or the returned reference may be used to complete configuration and build the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from building caches whose key or value types are incompatible with the types accepted by the weigher already provided; theCaffeine
type cannot do this. For best results, simply use the standard method-chaining idiom, as illustrated in the documentation at top, configuring aCaffeine
and building yourCache
all in a single statement.Warning: if you ignore the above advice, and use this
Caffeine
to build a cache whose key or value type is incompatible with the weigher, you will likely experience aClassCastException
at some undefined point in the future.- Type Parameters:
K1
- key type of the weigherV1
- value type of the weigher- Parameters:
weigher
- the weigher to use in calculating the weight of cache entries- Returns:
- the cache builder reference that should be used instead of
this
for any remaining configuration and cache building - Throws:
IllegalStateException
- if a weigher was already set
-
evicts
boolean evicts() -
isWeighted
boolean isWeighted() -
getMaximum
long getMaximum() -
getWeigher
-
weakKeys
Specifies that each key (not value) stored in the cache should be wrapped in aWeakReference
(by default, strong references are used).Warning: when this method is used, the resulting cache will use identity (
==
) comparison to determine equality of keys. ItsCache.asMap()
view will therefore technically violate theMap
specification (in the same way thatIdentityHashMap
does).Entries with keys that have been garbage collected may be counted in
Cache.estimatedSize()
, but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class javadoc.This feature cannot be used in conjunction with
writer
.This feature cannot be used in conjunction with
writer
or whenweakKeys()
is combined withbuildAsync()
.- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalStateException
- if the key strength was already set or the writer was set
-
isStrongKeys
boolean isStrongKeys() -
weakValues
Specifies that each value (not key) stored in the cache should be wrapped in aWeakReference
(by default, strong references are used).Weak values will be garbage collected once they are weakly reachable. This makes them a poor candidate for caching; consider
softValues()
instead.Note: when this method is used, the resulting cache will use identity (
==
) comparison to determine equality of values.Entries with values that have been garbage collected may be counted in
Cache.estimatedSize()
, but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class javadoc.This feature cannot be used in conjunction with
buildAsync()
.- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalStateException
- if the value strength was already set
-
isStrongValues
boolean isStrongValues() -
isWeakValues
boolean isWeakValues() -
softValues
Specifies that each value (not key) stored in the cache should be wrapped in aSoftReference
(by default, strong references are used). Softly-referenced objects will be garbage-collected in a globally least-recently-used manner, in response to memory demand.Warning: in most circumstances it is better to set a per-cache maximum size instead of using soft references. You should only use this method if you are very familiar with the practical consequences of soft references.
Note: when this method is used, the resulting cache will use identity (
==
) comparison to determine equality of values.Entries with values that have been garbage collected may be counted in
Cache.estimatedSize()
, but will never be visible to read or write operations; such entries are cleaned up as part of the routine maintenance described in the class javadoc.This feature cannot be used in conjunction with
buildAsync()
.- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalStateException
- if the value strength was already set
-
expireAfterWrite
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.Expired entries may be counted in
Cache.estimatedSize()
, 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. Ascheduler(Scheduler)
may be configured for a prompt removal of expired entries.- Parameters:
duration
- the length of time after an entry is created that it should be automatically removed- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is negativeIllegalStateException
- if the time to live or time to idle was already setArithmeticException
- for durations greater than +/- approximately 292 years
-
expireAfterWrite
public @NonNull Caffeine<K,V> expireAfterWrite(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull TimeUnit 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.Expired entries may be counted in
Cache.estimatedSize()
, 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. Ascheduler(Scheduler)
may be configured for a prompt removal of expired entries.If you can represent the duration as a
Duration
(which should be preferred when feasible), useexpireAfterWrite(Duration)
instead.- Parameters:
duration
- the length of time after an entry is created that it should be automatically removedunit
- the unit thatduration
is expressed in- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is negativeIllegalStateException
- if the time to live or variable expiration was already set
-
getExpiresAfterWriteNanos
long getExpiresAfterWriteNanos() -
expiresAfterWrite
boolean expiresAfterWrite() -
expireAfterAccess
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()
.Expired entries may be counted in
Cache.estimatedSize()
, 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. Ascheduler(Scheduler)
may be configured for a prompt removal of expired entries.- Parameters:
duration
- the length of time after an entry is last accessed that it should be automatically removed- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is negativeIllegalStateException
- if the time to idle or time to live was already setArithmeticException
- for durations greater than +/- approximately 292 years
-
expireAfterAccess
public @NonNull Caffeine<K,V> expireAfterAccess(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull 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 read. 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()
.Expired entries may be counted in
Cache.estimatedSize()
, 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. Ascheduler(Scheduler)
may be configured for a prompt removal of expired entries.If you can represent the duration as a
Duration
(which should be preferred when feasible), useexpireAfterAccess(Duration)
instead.- Parameters:
duration
- the length of time after an entry is last accessed that it should be automatically removedunit
- the unit thatduration
is expressed in- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is negativeIllegalStateException
- if the time to idle or variable expiration was already set
-
getExpiresAfterAccessNanos
long getExpiresAfterAccessNanos() -
expiresAfterAccess
boolean expiresAfterAccess() -
expireAfter
public <K1 extends K,V1 extends V> @NonNull Caffeine<K1,V1> expireAfter(@NonNull Expiry<? super K1, ? super V1> 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. The expiration 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()
.Expired entries may be counted in
Cache.estimatedSize()
, 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. Ascheduler(Scheduler)
may be configured for a prompt removal of expired entries.Important note: after invoking this method, do not continue to use this cache builder reference; instead use the reference this method returns. At runtime, these point to the same instance, but only the returned reference has the correct generic type information so as to ensure type safety. For best results, use the standard method-chaining idiom illustrated in the class documentation above, configuring a builder and building your cache in a single statement. Failure to heed this advice can result in a
ClassCastException
being thrown by a cache operation at some undefined point in the future.- Type Parameters:
K1
- key type of the weigherV1
- value type of the weigher- Parameters:
expiry
- the expiry to use in calculating the expiration time of cache entries- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalStateException
- if expiration was already set
-
expiresVariable
boolean expiresVariable() -
getExpiry
-
refreshAfterWrite
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. The semantics of refreshes are specified inLoadingCache.refresh(K)
, and are performed by callingCacheLoader.reload(K, V)
.Automatic refreshes are performed when the first stale request for an entry occurs. The request triggering refresh will make an asynchronous call to
CacheLoader.reload(K, V)
and immediately return the old value.Note: all exceptions thrown during refresh will be logged and then swallowed.
- Parameters:
duration
- the length of time after an entry is created that it should be considered stale, and thus eligible for refresh- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is zero or negativeIllegalStateException
- if the refresh interval was already setArithmeticException
- for durations greater than +/- approximately 292 years
-
refreshAfterWrite
public @NonNull Caffeine<K,V> refreshAfterWrite(@org.checkerframework.checker.index.qual.NonNegative long duration, @NonNull TimeUnit 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. The semantics of refreshes are specified inLoadingCache.refresh(K)
, and are performed by callingCacheLoader.reload(K, V)
.Automatic refreshes are performed when the first stale request for an entry occurs. The request triggering refresh will make an asynchronous call to
CacheLoader.reload(K, V)
and immediately return the old value.Note: all exceptions thrown during refresh will be logged and then swallowed.
If you can represent the duration as a
Duration
(which should be preferred when feasible), userefreshAfterWrite(Duration)
instead.- Parameters:
duration
- the length of time after an entry is created that it should be considered stale, and thus eligible for refreshunit
- the unit thatduration
is expressed in- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalArgumentException
- ifduration
is zero or negativeIllegalStateException
- if the refresh interval was already set
-
getRefreshAfterWriteNanos
long getRefreshAfterWriteNanos() -
refreshAfterWrite
boolean refreshAfterWrite() -
ticker
Specifies a nanosecond-precision time source for use in determining when entries should be expired or refreshed. By default,System.nanoTime()
is used.The primary intent of this method is to facilitate testing of caches which have been configured with
expireAfterWrite(java.time.Duration)
,expireAfterAccess(java.time.Duration)
, orrefreshAfterWrite(java.time.Duration)
.- Parameters:
ticker
- a nanosecond-precision time source- Returns:
- this
Caffeine
instance (for chaining) - Throws:
IllegalStateException
- if a ticker was already setNullPointerException
- if the specified ticker is null
-
getTicker
@NonNull Ticker getTicker() -
evictionListener
public <K1 extends K,V1 extends V> @NonNull Caffeine<K1,V1> evictionListener(@NonNull RemovalListener<? super K1, ? super V1> evictionListener) Specifies a listener instance that caches should notify each time an entry is evicted. The cache will invoke this listener during the atomic operation to remove the entry. In the case of expiration or reference collection, the entry may be pending removal and will be discarded as as part of the routine maintenance described in the class documentation above. For a more prompt notification on expiration ascheduler(Scheduler)
may be configured. AremovalListener(RemovalListener)
may be preferred when the listener should be invoked for any reason, be performed outside of the atomic operation to remove the entry, and delegated to the configuredexecutor(Executor)
.Important note: after invoking this method, do not continue to use this cache builder reference; instead use the reference this method returns. At runtime, these point to the same instance, but only the returned reference has the correct generic type information so as to ensure type safety. For best results, use the standard method-chaining idiom illustrated in the class documentation above, configuring a builder and building your cache in a single statement. Failure to heed this advice can result in a
ClassCastException
being thrown by a cache operation at some undefined point in the future.Warning: any exception thrown by
listener
will not be propagated to theCache
user, only logged via aLogger
.This feature cannot be used in conjunction when
weakKeys()
is combined withbuildAsync()
.- Type Parameters:
K1
- the key type of the listenerV1
- the value type of the listener- Parameters:
evictionListener
- a listener instance that caches should notify each time an entry is being automatically removed due to eviction- Returns:
- the cache builder reference that should be used instead of
this
for any remaining configuration and cache building - Throws:
IllegalStateException
- if a removal listener was already setNullPointerException
- if the specified removal listener is null
-
removalListener
public <K1 extends K,V1 extends V> @NonNull Caffeine<K1,V1> removalListener(@NonNull RemovalListener<? super K1, ? super V1> removalListener) Specifies a listener instance that caches should notify each time an entry is removed for any reason. The cache will invoke this listener on the configuredexecutor(Executor)
after the entry's removal operation has completed. In the case of expiration or reference collection, the entry may be pending removal and will be discarded as as part of the routine maintenance described in the class documentation above. For a more prompt notification on expiration ascheduler(Scheduler)
may be configured. AnevictionListener(RemovalListener)
may be preferred when the listener should be invoked as part of the atomic operation to remove the entry.Important note: after invoking this method, do not continue to use this cache builder reference; instead use the reference this method returns. At runtime, these point to the same instance, but only the returned reference has the correct generic type information so as to ensure type safety. For best results, use the standard method-chaining idiom illustrated in the class documentation above, configuring a builder and building your cache in a single statement. Failure to heed this advice can result in a
ClassCastException
being thrown by a cache operation at some undefined point in the future.Warning: any exception thrown by
listener
will not be propagated to theCache
user, only logged via aLogger
.- Type Parameters:
K1
- the key type of the listenerV1
- the value type of the listener- Parameters:
removalListener
- a listener instance that caches should notify each time an entry is removed- Returns:
- the cache builder reference that should be used instead of
this
for any remaining configuration and cache building - Throws:
IllegalStateException
- if a removal listener was already setNullPointerException
- if the specified removal listener is null
-
getRemovalListener
-
writer
@Deprecated public <K1 extends K,V1 extends V> @NonNull Caffeine<K1,V1> writer(@NonNull CacheWriter<? super K1, ? super V1> writer) Deprecated.Scheduled for removal in version 3.0.0. Consider instead usingMap
compute methods for extending manual write and remove operations, and usingevictionListener(RemovalListener)
for extending removals due to eviction.Specifies a writer instance that caches should notify each time an entry is explicitly created or modified, or removed for any reason. The writer is not notified when an entry is loaded or computed. Each cache created by this builder will invoke this writer as part of the atomic operation that modifies the cache.Important note: after invoking this method, do not continue to use this cache builder reference; instead use the reference this method returns. At runtime, these point to the same instance, but only the returned reference has the correct generic type information so as to ensure type safety. For best results, use the standard method-chaining idiom illustrated in the class documentation above, configuring a builder and building your cache in a single statement. Failure to heed this advice can result in a
ClassCastException
being thrown by a cache operation at some undefined point in the future.Warning: any exception thrown by
writer
will be propagated to theCache
user.This feature cannot be used in conjunction with
weakKeys()
,evictionListener(RemovalListener)
, orbuildAsync()
.- Type Parameters:
K1
- the key type of the writerV1
- the value type of the writer- Parameters:
writer
- a writer instance that caches should notify each time an entry is explicitly created or modified, or removed for any reason- Returns:
- the cache builder reference that should be used instead of
this
for any remaining configuration and cache building - Throws:
IllegalStateException
- if a writer was already set or if the key strength is weakNullPointerException
- if the specified writer is null
-
getCacheWriter
-
recordStats
Enables the accumulation ofCacheStats
during the operation of the cache. Without thisCache.stats()
will return zero for all statistics. Note that recording statistics requires bookkeeping to be performed with each operation, and thus imposes a performance penalty on cache operation.- Returns:
- this
Caffeine
instance (for chaining)
-
recordStats
public @NonNull Caffeine<K,V> recordStats(@NonNull Supplier<? extends StatsCounter> statsCounterSupplier) Enables the accumulation ofCacheStats
during the operation of the cache. Without thisCache.stats()
will return zero for all statistics. Note that recording statistics requires bookkeeping to be performed with each operation, and thus imposes a performance penalty on cache operation. Any exception thrown by the suppliedStatsCounter
will be suppressed and logged.- Parameters:
statsCounterSupplier
- a supplier instance that returns a newStatsCounter
- Returns:
- this
Caffeine
instance (for chaining)
-
isRecordingStats
boolean isRecordingStats() -
getStatsCounterSupplier
@NonNull Supplier<StatsCounter> getStatsCounterSupplier() -
isBounded
boolean isBounded() -
build
Builds a cache which does not automatically load values when keys are requested unless a mapping function is provided. Note that multiple threads can concurrently load values for distinct keys.Consider
build(CacheLoader)
instead, if it is feasible to implement aCacheLoader
.This method does not alter the state of this
Caffeine
instance, so it can be invoked again to create multiple independent caches.- Type Parameters:
K1
- the key type of the cacheV1
- the value type of the cache- Returns:
- a cache having the requested features
-
build
public <K1 extends K,V1 extends V> @NonNull LoadingCache<K1,V1> build(@NonNull 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
Caffeine
instance, so it can be invoked again to create multiple independent caches.- Type Parameters:
K1
- the key type of the loaderV1
- the value type of the loader- Parameters:
loader
- the cache loader used to obtain new values- 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. The returnedCompletableFuture
may be already loaded or currently computing the value for a given key. If the asynchronous computation fails or computes anull
value then the entry will be automatically removed. Note that multiple threads can concurrently load values for distinct keys.Consider
buildAsync(CacheLoader)
orbuildAsync(AsyncCacheLoader)
instead, if it is feasible to implement anCacheLoader
orAsyncCacheLoader
.This method does not alter the state of this
Caffeine
instance, so it can be invoked again to create multiple independent caches.This construction cannot be used with
weakValues()
,softValues()
,writer(CacheWriter)
, or whenweakKeys()
are combined withevictionListener(RemovalListener)
.- Type Parameters:
K1
- the key type of the cacheV1
- the value type of the cache- Returns:
- a cache having the requested features
-
buildAsync
public <K1 extends K,V1 extends V> @NonNull AsyncLoadingCache<K1,V1> buildAsync(@NonNull CacheLoader<? super K1, V1> loader) Builds a cache, which either returns aCompletableFuture
already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the suppliedCacheLoader
. If the asynchronous computation fails or computes anull
value then the entry will be automatically removed. Note that multiple threads can concurrently load values for distinct keys.This method does not alter the state of this
Caffeine
instance, so it can be invoked again to create multiple independent caches.This construction cannot be used with
weakValues()
,softValues()
,writer(CacheWriter)
, or whenweakKeys()
are combined withevictionListener(RemovalListener)
.- Type Parameters:
K1
- the key type of the loaderV1
- the value type of the loader- Parameters:
loader
- the cache loader used to obtain new values- Returns:
- a cache having the requested features
-
buildAsync
public <K1 extends K,V1 extends V> @NonNull AsyncLoadingCache<K1,V1> buildAsync(@NonNull AsyncCacheLoader<? super K1, V1> loader) Builds a cache, which either returns aCompletableFuture
already loaded or currently computing the value for a given key, or atomically computes the value asynchronously through a supplied mapping function or the suppliedAsyncCacheLoader
. If the asynchronous computation fails or computes anull
value then the entry will be automatically removed. Note that multiple threads can concurrently load values for distinct keys.This method does not alter the state of this
Caffeine
instance, so it can be invoked again to create multiple independent caches.This construction cannot be used with
weakValues()
,softValues()
,writer(CacheWriter)
, or whenweakKeys()
are combined withevictionListener(RemovalListener)
.- Type Parameters:
K1
- the key type of the loaderV1
- the value type of the loader- Parameters:
loader
- the cache loader used to obtain new values- Returns:
- a cache having the requested features
-
requireNonLoadingCache
void requireNonLoadingCache() -
requireWeightWithWeigher
void requireWeightWithWeigher() -
saturatedToNanos
Returns the number of nanoseconds of the given duration without throwing or overflowing.Instead of throwing
ArithmeticException
, this method silently saturates to eitherLong.MAX_VALUE
orLong.MIN_VALUE
. This behavior can be useful when decomposing a duration in order to call a legacy API which requires along, TimeUnit
pair. -
toString
Returns a string representation for this Caffeine instance. The exact form of the returned string is not specified.
-