Interface Cache<K,V>
-
- Type Parameters:
K
- type of the keyV
- type of the stores values
- All Superinterfaces:
AutoCloseable
,DataAware<K,V>
,KeyValueSource<K,V>
- All Known Implementing Classes:
AbstractCache
,ForwardingCache
public interface Cache<K,V> extends DataAware<K,V>, KeyValueSource<K,V>, AutoCloseable
A cache is similar to a map or a key value store, allowing to retrieve and update values which are associated with keys. In contrast to aHashMap
the cache allows concurrent access and modification to its content and automatically controls the amount of entries in the cache to stay within configured resource limits.A cache can be obtained via a
Cache2kBuilder
, for example:Cache<Long, List<String>> cache = new Cache2kBuilder<Long, List<String>>() {} .name("myCache") .eternal(true) .build();
Basic operation: To mutate and retrieve the cache content the operations
put(K, V)
andpeek(K)
can be used, for example:
It is important to note that the two assertion in the above example may fail. A cache has not the same guarantees as a data storage, because it needs to remove content automatically as soon as resource limits are reached. This is called eviction.cache.put(1, "one"); cache.put(2, "two"); // might fail: assertTrue(cache.containsKey(1)); assertEquals("two", cache.peek(2));
Populating: A cache may automatically populate its contents via a
CacheLoader
. For typical read mostly caching this has several advantages, for details seeCacheLoader
. When using a cache loader the additional methods for mutating the cache directly may not be needed. Some methods, that do not interact with the loader such ascontainsKey(K)
may be false friends. To make the code more obvious and protect against the accidental use of methods that do not invoke the loader transparently a subset interface, for example theKeyValueSource
can be used.CAS-Operations: The cache has a set of operations that examine an entry and do a mutation in an atomic way, for example
putIfAbsent(K, V)
,containsAndRemove(K)
andreplaceIfEquals(K, V, V)
. To allow arbitrary semantics that operate atomically on anEntryProcessor
can be implemented and executed viainvoke(K, org.cache2k.processor.EntryProcessor<K, V, R>)
.Compatibility: Future versions of cache2k may introduce new methods to this interface. To improve upward compatibility applications that need to implement this interface should use
AbstractCache
orForwardingCache
.- Author:
- Jens Wilke
- See Also:
to create a cache
,to manage and retrieve created caches
, cache2k User Guide
-
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description ConcurrentMap<K,V>
asMap()
Returns a map interface for operating with this cache.void
clear()
Clear the cache in a fast way, causing minimal disruption.void
close()
Release resources in the local VM and remove the cache from the CacheManager.V
computeIfAbsent(K key, Function<? super K,? extends V> function)
If the specified key is not already associated with a value (or exception), call the provided task and associate it with the returned value.boolean
containsAndRemove(K key)
Check for existing mapping and remove it.boolean
containsKey(K key)
Returnstrue
, if there is a mapping for the specified key.Set<CacheEntry<K,V>>
entries()
All entries in the cache.void
expireAt(K key, long time)
Updates an existing not expired mapping to expire at the given point in time.V
get(K key)
Returns a value associated with the given key.Map<K,V>
getAll(Iterable<? extends K> keys)
Retrieve values from the cache associated with the provided keys.CacheManager
getCacheManager()
Return the cache manager for this cache instance.@Nullable CacheEntry<K,V>
getEntry(K key)
Returns an entry that contains the cache value associated with the given key.String
getName()
A configured or generated name of this cache instance.<@Nullable R>
Rinvoke(K key, EntryProcessor<K,V,@Nullable R> processor)
Invoke a user defined function on a cache entry.<@Nullable R>
Map<K,EntryProcessingResult<R>>invokeAll(Iterable<? extends K> keys, EntryProcessor<K,V,@Nullable R> entryProcessor)
Invoke a user defined function on multiple cache entries specified by thekeys
parameter.boolean
isClosed()
Returnstrue
if cache was closed or closing is in progress.Set<K>
keys()
A set view of all keys in the cache.CompletableFuture<Void>
loadAll(Iterable<? extends K> keys)
Request to load the given set of keys into the cache.default void
mutate(K key, EntryMutator<K,V> mutator)
Invoke a user defined operation on a cache entry.default void
mutateAll(Iterable<? extends K> keys, EntryMutator<K,V> mutator)
Invoke a user defined mutation operation on multiple cache entries specified by thekeys
parameter.V
peek(K key)
Returns the value associated to the given key.Map<K,V>
peekAll(Iterable<? extends K> keys)
Bulk version forpeek(Object)
V
peekAndPut(K key, V value)
Updates an existing cache entry for the specified key, so it associates the given value, or, insert a new cache entry for this key and value.V
peekAndRemove(K key)
Removes the mapping for a key from the cache if it is present.V
peekAndReplace(K key, V value)
Replaces the entry for a key only if currently mapped to some value.@Nullable CacheEntry<K,V>
peekEntry(K key)
Returns an entry that contains the cache value associated with the given key.void
put(K key, V value)
Inserts a new value associated with the given key or updates an existing association of the same key with the new value.void
putAll(Map<? extends K,? extends V> valueMap)
Insert all elements of the map into the cache.boolean
putIfAbsent(K key, V value)
If the specified key is not already associated with a value, associate it with the given value.CompletableFuture<Void>
reloadAll(Iterable<? extends K> keys)
Request to load the given set of keys into the cache.void
remove(K key)
Removes the mapping for a key from the cache if it is present.void
removeAll()
Removes all cache contents.void
removeAll(Iterable<? extends K> keys)
Removes a set of keys.boolean
removeIfEquals(K key, V expectedValue)
Remove the mapping if the stored value is equal to the comparison value.boolean
replace(K key, V value)
Replaces the entry for a key only if currently mapped to some value.boolean
replaceIfEquals(K key, V oldValue, V newValue)
Replaces the entry for a key only if currently mapped to a given value.<T> T
requestInterface(Class<T> type)
Request an alternative interface for this cache instance.String
toString()
Returns internal information.
-
-
-
Method Detail
-
getName
String getName()
A configured or generated name of this cache instance. A cache in close state will still return its name.- Returns:
- name of this cache
- See Also:
Cache2kBuilder.name(String)
-
get
@Nullable V get(K key)
Returns a value associated with the given key. If no value is present, or it is expired the cache loader is invoked, if configured, ornull
is returned.If the
CacheLoader
is invoked, subsequent requests of the same key will block until the loading is completed. Details seeCacheLoader
.As an alternative
peek(K)
can be used if the loader should not be invoked.- Specified by:
get
in interfaceKeyValueSource<K,V>
- Parameters:
key
- key with which the specified value is associated- Returns:
- the value associated with the specified key, or
null
if there was no mapping for the key. (If nulls are permitted anull
can also indicate that the cache previously associatednull
with the key) - Throws:
ClassCastException
- if the class of the specified key prevents it from being stored in this cacheNullPointerException
- if the specified key isnull
IllegalArgumentException
- if some property of the specified key prevents it from being stored in this cacheCacheLoaderException
- if the loading produced an exception .- See Also:
get(Object)
-
getEntry
@Nullable @Nullable CacheEntry<K,V> getEntry(K key)
Returns an entry that contains the cache value associated with the given key. If no entry is present or the value is expired, either the loader is invoked ornull
is returned.If the loader is invoked, subsequent requests of the same key will block until the loading is completed, details see
CacheLoader
In case the cache loader yields an exception, the entry object will be returned. The exception can be retrieved via
CacheEntry.getException()
.If
null
values are present the method can be used to check for an existent mapping and retrieve the value in one API call.The alternative method
peekEntry(K)
can be used if the loader should not be invoked.- Parameters:
key
- key to retrieve the associated with the cache entry- Returns:
- An entry representing the cache mapping. Multiple calls for the same key may return different instances of the entry object.
- Throws:
ClassCastException
- if the class of the specified key prevents it from being stored in this cacheNullPointerException
- if the specified key is nullIllegalArgumentException
- if some property of the specified key prevents it from being stored in this cache
-
peek
@Nullable V peek(K key)
Returns the value associated to the given key.In contrast to
get(Object)
this method solely operates on the cache content and does not invoke the cache loader.API rationale: Consequently all methods that do not invoke the loader but return a value or a cache entry are prefixed with
peek
within this interface to make the different semantics immediately obvious by the name.- Parameters:
key
- key with which the specified value is associated- Returns:
- the value associated with the specified key, or
null
if there was no mapping for the key. (If nulls are permitted anull
can also indicate that the cache previously associatednull
with the key) - Throws:
ClassCastException
- if the class of the specified key prevents it from being stored in this cacheNullPointerException
- if the specified key is nullIllegalArgumentException
- if some property of the specified key prevents it from being stored in this cacheCacheLoaderException
- if the loading produced an exception .
-
peekEntry
@Nullable @Nullable CacheEntry<K,V> peekEntry(K key)
Returns an entry that contains the cache value associated with the given key. If no entry is present or the value is expired,null
is returned. The cache loader will not be invoked by this method.In case an exception is present, for example from a load operation carried out previously, the entry object will be returned. The exception can be retrieved via
CacheEntry.getException()
.If
null
values are present the method can be used to check for an existent mapping and retrieve the value in one API call.- Parameters:
key
- key to retrieve the associated with the cache entry- Returns:
- An entry representing the cache mapping. Multiple calls for the same key may return different instances of the entry object.
- Throws:
ClassCastException
- if the class of the specified key prevents it from being stored in this cacheNullPointerException
- if the specified key is nullIllegalArgumentException
- if some property of the specified key prevents it from being stored in this cache
-
containsKey
boolean containsKey(K key)
Returnstrue
, if there is a mapping for the specified key.Effect on statistics: The operation does increase the usage counter if a mapping is present, but does not count as read and therefore does not influence miss or hit values.
- Parameters:
key
- key which association should be checked- Returns:
true
, if this cache contains a mapping for the specified key- Throws:
ClassCastException
- if the key is of an inappropriate type for this cacheNullPointerException
- if the specified key is null
-
put
void put(K key, V value)
Inserts a new value associated with the given key or updates an existing association of the same key with the new value.If an
ExpiryPolicy
is specified in the cache configuration it is called and will determine the expiry time. If aCacheWriter
is registered, then it is called with the new value. If theExpiryPolicy
orCacheWriter
yield an exception the operation will be aborted and the previous mapping will be preserved.- Parameters:
key
- key with which the specified value is associatedvalue
- value to be associated with the specified key- Throws:
ClassCastException
- if the class of the specified key or value prevents it from being stored in this cache.NullPointerException
- if the specified key is null or the value is null and the cache does not permit null valuesIllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this cache.CacheException
- if the cache was unable to process the request completely, for example, if an exceptions was thrown by aCacheWriter
-
computeIfAbsent
V computeIfAbsent(K key, Function<? super K,? extends V> function)
If the specified key is not already associated with a value (or exception), call the provided task and associate it with the returned value. This is equivalent toif (!cache.containsKey(key)) { V value = function.apply(key); cache.put(key, value); return value; } else { return cache.peek(key); }
Map.computeIfAbsent(Object, Function)
semantics, which treat a null value as absent.See
put(Object, Object)
for the effects on the cache writer and expiry calculation.Statistics: If an entry exists this operation counts as a hit, if the entry is missing, a miss and put is counted.
Exceptions: If the call throws an exception the cache contents will not be modified and the exception is propagated.
- Parameters:
key
- key with which the specified value is to be associatedfunction
- task that computes the value- Returns:
- the cached value or the result of the compute operation if no mapping is present
- Throws:
RuntimeException
- in case function yields a runtime exception, this is thrown directlyNullPointerException
- if the specified key isnull
or the value isnull
and the cache does not permitnull
valuesCacheLoaderException
- Depending on theResiliencePolicy
the cache entry may hold a loader exception which is rethrown via theExceptionPropagator
-
putIfAbsent
boolean putIfAbsent(K key, V value)
If the specified key is not already associated with a value, associate it with the given value. This is equivalent toif (!cache.containsKey(key)) { cache.put(key, value); return true; } else { return false; }
Map.putIfAbsent(Object, Object)
semantics, which treat a null value as absent.See
put(Object, Object)
for the effects on the cache writer and expiry calculation.Statistics: If an entry exists this operation counts as a hit, if the entry is missing, a miss and put is counted. This definition is identical to the JSR107 statistics semantics. This is not consistent with other operations like
containsAndRemove(Object)
andcontainsKey(Object)
that don't update the hit or miss counter if solely the existence of an entry is tested and not the value itself is requested. This counting is subject to discussion and future change.- Parameters:
key
- key with which the specified value is to be associatedvalue
- value to be associated with the specified key- Returns:
true
, if no entry was present and the value was associated with the key- Throws:
ClassCastException
- if the class of the specified key or value prevents it from being stored in this cacheNullPointerException
- if the specified key is null or the value is null and the cache does not permit null valuesIllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this cache
-
peekAndReplace
@Nullable V peekAndReplace(K key, V value)
Replaces the entry for a key only if currently mapped to some value. This is equivalent toif (cache.containsKey(key)) { cache.put(key, value); return cache.peek(key); } else return null;
As with
peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.- Parameters:
key
- key with which the specified value is associatedvalue
- value to be associated with the specified key- Returns:
- the previous value associated with the specified key, or
null
if there was no mapping for the key. (Anull
return can also indicate that the cache previously associatednull
with the key) - Throws:
ClassCastException
- if the class of the specified key or value prevents it from being stored in this cacheNullPointerException
- if the specified key is null or the value is null and the cache does not permit null valuesIllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this cacheCacheLoaderException
- if the loading of the entry produced an exception, which was not suppressed and is not yet expired
-
replace
boolean replace(K key, V value)
Replaces the entry for a key only if currently mapped to some value. This is equivalent toif (cache.containsKey(key)) { cache.put(key, value); return true } else return false;
Statistics: If an entry exists this operation counts as a hit, if the entry is missing, a miss and put is counted. This definition is identical to the JSR107 statistics semantics. This is not consistent with other operations like
containsAndRemove(Object)
andcontainsKey(Object)
that don't update the hit or miss counter if solely the existence of an entry is tested and not the value itself is requested. This counting is subject to discussion and future change.- Parameters:
key
- key with which the specified value is associatedvalue
- value to be associated with the specified key- Returns:
true
if a mapping is present and the value was replaced.false
if no entry is present and no action was performed.- Throws:
ClassCastException
- if the class of the specified key or value prevents it from being stored in this cache.NullPointerException
- if the specified key is null or the value is null and the cache does not permit null valuesIllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this cache.
-
replaceIfEquals
boolean replaceIfEquals(K key, V oldValue, V newValue)
Replaces the entry for a key only if currently mapped to a given value. This is equivalent toif (cache.containsKey(key) && Objects.equals(cache.get(key), oldValue)) { cache.put(key, newValue); return true; } else return false;
- Parameters:
key
- key with which the specified value is associatedoldValue
- value expected to be associated with the specified keynewValue
- value to be associated with the specified key- Returns:
true
if the value was replaced- Throws:
ClassCastException
- if the class of a specified key or value prevents it from being stored in this mapNullPointerException
- if a specified key or value is null, and this map does not permit null keys or valuesIllegalArgumentException
- if some property of a specified key or value prevents it from being stored in this map
-
peekAndRemove
@Nullable V peekAndRemove(K key)
Removes the mapping for a key from the cache if it is present.Returns the value to which the cache previously associated the key, or
null
if the cache contained no mapping for the key.If the cache does permit null values, then a return value of
null
does not necessarily indicate that the cache contained no mapping for the key. It is also possible that the cache explicitly associated the key to the valuenull
. This is equivalent toV tmp = cache.peek(key); cache.remove(key); return tmp;
As with
peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.- Parameters:
key
- key whose mapping is to be removed from the cache- Returns:
- the previous value associated with the specified key, or
null
if there was no mapping for the key. (Anull
can also indicate that the cache previously associated the valuenull
with the key) - Throws:
NullPointerException
- if a specified key is nullClassCastException
- if the key is of an inappropriate type for the cache. This check is optional depending on the cache configuration.
-
containsAndRemove
boolean containsAndRemove(K key)
Check for existing mapping and remove it.- Parameters:
key
- key to be checked and removed- Returns:
true
if the cache contained a mapping for the specified key- Throws:
NullPointerException
- if the specified key isnull
ClassCastException
- if the key is of an inappropriate type for the cache. This check is optional depending on the cache configuration.
-
remove
void remove(K key)
Removes the mapping for a key from the cache if it is present.If a writer is registered
CacheWriter.delete(Object)
will get called.These alternative versions of the remove operation exist:
containsAndRemove(Object)
, returning a success flagpeekAndRemove(Object)
, returning the removed valueremoveIfEquals(Object, Object)
, conditional removal matching on the current value
Rationale: It is intentional that this method does not return a boolean or the previous entry. When operating in cache through configuration (which means a
CacheWriter
andCacheLoader
is registered) a boolean could mean two different things: the value was present in the cache or the value was present in the system of authority. The purpose of this interface is a reduced set of methods that cannot be misinterpreted.- Parameters:
key
- key which mapping is to be removed from the cache, not null- Throws:
NullPointerException
- if a specified key is nullClassCastException
- if the key is of an inappropriate type for this mapCacheWriterException
- if the writer call failed
-
removeIfEquals
boolean removeIfEquals(K key, V expectedValue)
Remove the mapping if the stored value is equal to the comparison value.If no mapping exists, this method will do nothing and return
false
, even if the tested value isnull
.- Parameters:
key
- key whose mapping is to be removed from the cacheexpectedValue
- value that must match with the existing value in the cache. It is also possible to check whether the value isnull
.- Returns:
true
, if mapping was removed- Throws:
NullPointerException
- if a specified key isnull
ClassCastException
- if the key is of an inappropriate type for this map
-
removeAll
void removeAll(Iterable<? extends K> keys)
Removes a set of keys. This has the same semantics of calling remove to every key, except that the cache is trying to optimize the bulk operation.- Parameters:
keys
- a set of keys to remove- Throws:
NullPointerException
- if a specified key is null
-
peekAndPut
@Nullable V peekAndPut(K key, V value)
Updates an existing cache entry for the specified key, so it associates the given value, or, insert a new cache entry for this key and value. The previous value will be returned, or null if none was available.Returns the value to which the cache previously associated the key, or
null
if the cache contained no mapping for the key.If the cache does permit null values, then a return value of
null
does not necessarily indicate that the cache contained no mapping for the key. It is also possible that the cache explicitly associated the key to the valuenull
. This is equivalent toV tmp = cache.peek(key); cache.put(key, value); return tmp;
As with
peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.See
put(Object, Object)
for the effects on the cache writer and expiry calculation.- Parameters:
key
- key with which the specified value is associatedvalue
- value to be associated with the specified key- Returns:
- the previous value associated with the specified key, or
null
if there was no mapping for the key. (Anull
return can also indicate that the cache previously associatednull
with the key) - Throws:
ClassCastException
- if the class of the specified key or value prevents it from being stored in this cache.NullPointerException
- if the specified key is null or the value is null and the cache does not permit null valuesIllegalArgumentException
- if some property of the specified key or value prevents it from being stored in this cache.
-
expireAt
void expireAt(K key, long time)
Updates an existing not expired mapping to expire at the given point in time. If there is no mapping associated with the key, or it is already expired, this operation has no effect. The special valuesExpiryTimeValues.NOW
andExpiryTimeValues.REFRESH
also effect an entry that was just refreshed.If the expiry time is in the past, the entry will expire immediately and refresh ahead is triggered, if enabled.
Although the special time value
ExpiryTimeValues.NOW
will lead to an effective removal of the cache entry, the writer is not called, since the method is for cache control only.It is possible to insert a value and set a custom expiry time atomically via
invoke(Object, EntryProcessor)
andMutableCacheEntry.setExpiryTime(long)
.The effective time will be capped based on the setting of
Cache2kBuilder.expireAfterWrite(Duration)
- Parameters:
key
- key with which the specified value is associatedtime
- millis since epoch or as defined byTimeReference
. Some values have special meanings, seeExpiryTimeValues
- Throws:
IllegalArgumentException
- if expiry was disabled viaCache2kBuilder.eternal(boolean)
-
loadAll
CompletableFuture<Void> loadAll(Iterable<? extends K> keys)
Request to load the given set of keys into the cache. Only missing or expired values will be loaded. The method returns immediately with aCompletableFuture
. If no asynchronous loader is specified, the executor specified byCache2kBuilder.loaderExecutor(Executor)
will be used.The cache uses multiple threads to load the values in parallel. If thread resources are not sufficient, meaning the used executor is throwing
RejectedExecutionException
the calling thread is used to produce back pressure.If no loader is defined, the method will throw an immediate exception.
The operation will return a
CacheLoaderException
in case of a call to the loader threw an exception. If resilience is used and exceptions are cached, this also applied to cached exceptions. Thus, the operation completes successful only if all values were loaded successfully.When a load is performed each entry is blocked for other requests. See {@see org.cache2k.io.AsyncBulkCacheLoader} for detailed description.
- Parameters:
keys
- The keys to be loaded- Returns:
- future getting notified on completion
- Throws:
UnsupportedOperationException
- if no loader is defined
-
reloadAll
CompletableFuture<Void> reloadAll(Iterable<? extends K> keys)
Request to load the given set of keys into the cache. Missing or expired values will be loaded aCompletableFuture
. The method returns immediately with aCompletableFuture
. If no asynchronous loader is specified, the executor specified byCache2kBuilder.loaderExecutor(Executor)
will be used.The cache uses multiple threads to load the values in parallel. If thread resources are not sufficient, meaning the used executor is throwing
RejectedExecutionException
the calling thread is used to produce back pressure.If no loader is defined, the method will throw an immediate exception.
When a load is performed each entry is blocked for other requests. See {@see org.cache2k.io.AsyncBulkCacheLoader} for detailed description.
- Parameters:
keys
- The keys to be loaded- Returns:
- future getting notified on completion
- Throws:
UnsupportedOperationException
- if no loader is defined
-
invoke
@Nullable <@Nullable R> R invoke(K key, EntryProcessor<K,V,@Nullable R> processor)
Invoke a user defined function on a cache entry. For examples and further details consult the documentation ofEntryProcessor
andMutableCacheEntry
.- Type Parameters:
R
- type of the result- Parameters:
key
- the key of the cache entry that should be processedprocessor
- processor instance to be invoked- Returns:
- result provided by the entry processor
- Throws:
EntryProcessingException
- if an exception happened insideEntryProcessor.process(MutableCacheEntry)
- See Also:
EntryProcessor
,MutableCacheEntry
-
mutate
default void mutate(K key, EntryMutator<K,V> mutator)
Invoke a user defined operation on a cache entry. For examples and further details consult the documentation ofEntryProcessor
andMutableCacheEntry
.- Parameters:
key
- the key of the cache entry that should be processedmutator
- processor instance to be invoked- Throws:
EntryProcessingException
- if an exception happened insideEntryProcessor.process(MutableCacheEntry)
- Since:
- 2.0
- See Also:
EntryProcessor
,MutableCacheEntry
-
invokeAll
<@Nullable R> Map<K,EntryProcessingResult<R>> invokeAll(Iterable<? extends K> keys, EntryProcessor<K,V,@Nullable R> entryProcessor)
Invoke a user defined function on multiple cache entries specified by thekeys
parameter.The order of the invocation is unspecified. To speed up processing the cache may invoke the entry processor in parallel. For examples and further details consult the documentation of
EntryProcessor
andMutableCacheEntry
.- Type Parameters:
R
- type of the result- Parameters:
keys
- the keys of the cache entries that should be processedentryProcessor
- processor instance to be invoked- Returns:
- An immutable map containing the invocation results for every cache key
- See Also:
EntryProcessor
,MutableCacheEntry
-
mutateAll
default void mutateAll(Iterable<? extends K> keys, EntryMutator<K,V> mutator)
Invoke a user defined mutation operation on multiple cache entries specified by thekeys
parameter.The order of the invocation is unspecified. To speed up processing the cache may invoke the entry processor in parallel. For examples and further details consult the documentation of
EntryProcessor
andMutableCacheEntry
.- Parameters:
keys
- the keys of the cache entries that should be processedmutator
- processor instance to be invoked- Since:
- 2.0
- See Also:
EntryProcessor
,MutableCacheEntry
-
getAll
Map<K,V> getAll(Iterable<? extends K> keys)
Retrieve values from the cache associated with the provided keys. If the value is not yet in the cache, the loader is invoked.Executing the request, the cache may do optimizations like utilizing multiple threads for invoking the loader or using the bulk methods on the loader. When a load is performed each entry is blocked for other requests. See {@see org.cache2k.io.AsyncBulkCacheLoader} for detailed description.
Exception handling: In case of loader exceptions, the method will throw an immediate exception if the load for all requested keys resulted in an exception or another problem occurred. If some keys were loaded successfully the method will return a map and terminate without exception, but requesting the faulty value from the map returns an exception.
The operation is not performed atomically.
- Returns:
- an immutable map with the requested values
- Throws:
NullPointerException
- if one of the specified keys is nullCacheLoaderException
- in case the loader has permanent failures. Otherwise, the exception is thrown when the key is requested.
-
peekAll
Map<K,V> peekAll(Iterable<? extends K> keys)
Bulk version forpeek(Object)
If the cache permits null values, the map will contain entries mapped to a null value.
If the loading of an entry produced an exception, which was not suppressed and is not yet expired. This exception will be thrown as
CacheLoaderException
when the entry is accessed via the map interface.The operation is not performed atomically. Mutations of the cache during this operation may or may not affect the result.
- Throws:
NullPointerException
- if one of the specified keys is nullIllegalArgumentException
- if some property of the specified key prevents it from being stored in this cache
-
putAll
void putAll(Map<? extends K,? extends V> valueMap)
Insert all elements of the map into the cache.See
put(Object, Object)
for information about the interaction with theCacheWriter
andExpiryPolicy
- Parameters:
valueMap
- Map of keys with associated values to be inserted in the cache- Throws:
NullPointerException
- if one of the specified keys is null
-
keys
Set<K> keys()
A set view of all keys in the cache. The set is guaranteed containing all keys present in the cache at the time of calling the method, and may or may not reflect concurrent inserts or removals.Contract: An iteration or stream is usable while concurrent operations happen on the cache. All entry keys will be iterated when present in the cache at the moment of the call to
Set.iterator()
. An expiration or mutation happening during the iteration, may or may not be reflected. It is ensured that every key is only iterated once.The iterator itself is not thread safe. Calls to one iterator instance from different threads are illegal or need proper synchronization.
Statistics: Iteration is neutral to the cache statistics.
Efficiency: Iterating keys is faster as iterating complete entries.
-
entries
Set<CacheEntry<K,V>> entries()
All entries in the cache.See
keys()
for the general contract.Efficiency: Iterating entries is less efficient than just iterating keys. The cache needs to create a new entry object and employ some sort of synchronisation to supply a consistent and immutable entry.
- See Also:
keys()
-
removeAll
void removeAll()
Removes all cache contents. This has the same semantics of calling remove to every key, except that the cache is trying to optimize the bulk operation. Same asclear
but listeners will be called. An alternative version for improved parallel processing is available atCacheOperation.removeAll()
-
clear
void clear()
Clear the cache in a fast way, causing minimal disruption. Not calling the listeners. An alternative version for improved parallel processing is available atCacheOperation.clear()
-
close
void close()
Release resources in the local VM and remove the cache from the CacheManager.The method is designed to free resources and finish operations as gracefully and fast as possible. Some cache operations take an unpredictable long time such as the call of the
CacheLoader
, so it may happen that the cache still has threads in use when this method returns.After close, subsequent cache operations will throw a
IllegalStateException
. Cache operations currently in progress, may or may not be terminated with an exception. A subsequent call to close will not throw an exception.If all caches need to be closed it is more effective to use
CacheManager.close()
An alternative version for improved parallel processing is available at
CacheOperation.close()
- Specified by:
close
in interfaceAutoCloseable
-
getCacheManager
CacheManager getCacheManager()
Return the cache manager for this cache instance.
-
isClosed
boolean isClosed()
Returnstrue
if cache was closed or closing is in progress.
-
toString
String toString()
Returns internal information. This is an expensive operation, since internal statistics are collected. During the call, concurrent operations on the cache may be blocked. This method will not throw theIllegalStateException
in case the cache is closed, but return only the cache name and no statistics.
-
requestInterface
<T> T requestInterface(Class<T> type)
Request an alternative interface for this cache instance.- Throws:
UnsupportedOperationException
- if interface is not availableIllegalStateException
- if cache is closed
-
asMap
ConcurrentMap<K,V> asMap()
Returns a map interface for operating with this cache. Operations on the map affect the cache directly, as well as modifications on the cache will affect the map.The returned map supports
null
values if enabled viaCache2kBuilder.permitNullValues(boolean)
.The
equals
andhashCode
methods of theMap
are forwarded to the cache. A map is considered identical when from the same cache instance. This is not compatible to the generalMap
contract.Operations on the map do not invoke the loader.
Multiple calls to this method return a new object instance which is a wrapper of the cache instance. Calling this method is a cheap operation.
- Returns:
ConcurrentMap
wrapper for this cache instance
-
-