Class AbstractCache<K,V>
- java.lang.Object
-
- org.cache2k.AbstractCache<K,V>
-
- All Implemented Interfaces:
AutoCloseable
,Cache<K,V>
,DataAware<K,V>
,KeyValueSource<K,V>
public class AbstractCache<K,V> extends Object implements Cache<K,V>
Base class for implementations of the cache interface. By default, every method throwsUnsupportedOperationException
.- Author:
- Jens Wilke
-
-
Constructor Summary
Constructors Constructor Description AbstractCache()
-
Method Summary
All Methods Instance Methods Concrete 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.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.void
mutate(K key, EntryMutator<K,V> mutator)
Invoke a user defined operation on a cache entry.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 forCache.peek(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.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.<X> X
requestInterface(Class<X> type)
Request an alternative interface for this cache instance.String
toString()
Returns internal information.
-
-
-
Method Detail
-
getName
public String getName()
Description copied from interface:Cache
A configured or generated name of this cache instance. A cache in close state will still return its name.- Specified by:
getName
in interfaceCache<K,V>
- Returns:
- name of this cache
- See Also:
Cache2kBuilder.name(String)
-
get
@Nullable public V get(K key)
Description copied from interface:Cache
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
Cache.peek(K)
can be used if the loader should not be invoked.- Specified by:
get
in interfaceCache<K,V>
- 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) - See Also:
Cache.get(Object)
-
getEntry
public CacheEntry<K,V> getEntry(K key)
Description copied from interface:Cache
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
Cache.peekEntry(K)
can be used if the loader should not be invoked.
-
peek
public V peek(K key)
Description copied from interface:Cache
Returns the value associated to the given key.In contrast to
Cache.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.- Specified by:
peek
in interfaceCache<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)
-
peekEntry
public CacheEntry<K,V> peekEntry(K key)
Description copied from interface:Cache
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.
-
containsKey
public boolean containsKey(K key)
Description copied from interface:Cache
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.
- Specified by:
containsKey
in interfaceCache<K,V>
- Parameters:
key
- key which association should be checked- Returns:
true
, if this cache contains a mapping for the specified key
-
put
public void put(K key, V value)
Description copied from interface:Cache
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.
-
computeIfAbsent
public V computeIfAbsent(K key, Function<? super K,? extends V> function)
Description copied from interface:Cache
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
Cache.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.
- Specified by:
computeIfAbsent
in interfaceCache<K,V>
- 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
-
putIfAbsent
public boolean putIfAbsent(K key, V value)
Description copied from interface:Cache
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
Cache.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
Cache.containsAndRemove(Object)
andCache.containsKey(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.- Specified by:
putIfAbsent
in interfaceCache<K,V>
- 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
-
peekAndReplace
@Nullable public V peekAndReplace(K key, V value)
Description copied from interface:Cache
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
Cache.peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.- Specified by:
peekAndReplace
in interfaceCache<K,V>
- 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)
-
replace
public boolean replace(K key, V value)
Description copied from interface:Cache
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
Cache.containsAndRemove(Object)
andCache.containsKey(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.
-
replaceIfEquals
public boolean replaceIfEquals(K key, V oldValue, V newValue)
Description copied from interface:Cache
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;
- Specified by:
replaceIfEquals
in interfaceCache<K,V>
- 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
-
peekAndRemove
@Nullable public V peekAndRemove(K key)
Description copied from interface:Cache
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
Cache.peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.- Specified by:
peekAndRemove
in interfaceCache<K,V>
- 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)
-
containsAndRemove
public boolean containsAndRemove(K key)
Description copied from interface:Cache
Check for existing mapping and remove it.- Specified by:
containsAndRemove
in interfaceCache<K,V>
- Parameters:
key
- key to be checked and removed- Returns:
true
if the cache contained a mapping for the specified key
-
remove
public void remove(K key)
Description copied from interface:Cache
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:
Cache.containsAndRemove(Object)
, returning a success flagCache.peekAndRemove(Object)
, returning the removed valueCache.removeIfEquals(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.
-
removeIfEquals
public boolean removeIfEquals(K key, V expectedValue)
Description copied from interface:Cache
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
.- Specified by:
removeIfEquals
in interfaceCache<K,V>
- 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
-
removeAll
public void removeAll(Iterable<? extends K> keys)
Description copied from interface:Cache
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.
-
peekAndPut
public V peekAndPut(K key, V value)
Description copied from interface:Cache
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
Cache.peek(Object)
, no request to theCacheLoader
is made, if no entry is associated to the requested key.See
Cache.put(Object, Object)
for the effects on the cache writer and expiry calculation.- Specified by:
peekAndPut
in interfaceCache<K,V>
- 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)
-
expireAt
public void expireAt(K key, long time)
Description copied from interface:Cache
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
Cache.invoke(Object, EntryProcessor)
andMutableCacheEntry.setExpiryTime(long)
.The effective time will be capped based on the setting of
Cache2kBuilder.expireAfterWrite(Duration)
- Specified by:
expireAt
in interfaceCache<K,V>
- Parameters:
key
- key with which the specified value is associatedtime
- millis since epoch or as defined byTimeReference
. Some values have special meanings, seeExpiryTimeValues
-
loadAll
public CompletableFuture<Void> loadAll(Iterable<? extends K> keys)
Description copied from interface:Cache
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.
-
reloadAll
public CompletableFuture<Void> reloadAll(Iterable<? extends K> keys)
Description copied from interface:Cache
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.
-
invoke
public <@Nullable R> R invoke(K key, EntryProcessor<K,V,@Nullable R> processor)
Description copied from interface:Cache
Invoke a user defined function on a cache entry. For examples and further details consult the documentation ofEntryProcessor
andMutableCacheEntry
.- Specified by:
invoke
in interfaceCache<K,V>
- 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
- See Also:
EntryProcessor
,MutableCacheEntry
-
invokeAll
public <@Nullable R> Map<K,EntryProcessingResult<R>> invokeAll(Iterable<? extends K> keys, EntryProcessor<K,V,@Nullable R> entryProcessor)
Description copied from interface:Cache
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
.- Specified by:
invokeAll
in interfaceCache<K,V>
- 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
-
mutate
public void mutate(K key, EntryMutator<K,V> mutator)
Description copied from interface:Cache
Invoke a user defined operation on a cache entry. For examples and further details consult the documentation ofEntryProcessor
andMutableCacheEntry
.- Specified by:
mutate
in interfaceCache<K,V>
- Parameters:
key
- the key of the cache entry that should be processedmutator
- processor instance to be invoked- See Also:
EntryProcessor
,MutableCacheEntry
-
mutateAll
public void mutateAll(Iterable<? extends K> keys, EntryMutator<K,V> mutator)
Description copied from interface:Cache
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
.- Specified by:
mutateAll
in interfaceCache<K,V>
- Parameters:
keys
- the keys of the cache entries that should be processedmutator
- processor instance to be invoked- See Also:
EntryProcessor
,MutableCacheEntry
-
getAll
public Map<K,V> getAll(Iterable<? extends K> keys)
Description copied from interface:Cache
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.
-
peekAll
public Map<K,V> peekAll(Iterable<? extends K> keys)
Description copied from interface:Cache
Bulk version forCache.peek(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.
-
putAll
public void putAll(Map<? extends K,? extends V> valueMap)
Description copied from interface:Cache
Insert all elements of the map into the cache.See
Cache.put(Object, Object)
for information about the interaction with theCacheWriter
andExpiryPolicy
-
keys
public Set<K> keys()
Description copied from interface:Cache
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
public Set<CacheEntry<K,V>> entries()
Description copied from interface:Cache
All entries in the cache.See
Cache.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.
- Specified by:
entries
in interfaceCache<K,V>
- See Also:
Cache.keys()
-
removeAll
public void removeAll()
Description copied from interface:Cache
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
public void clear()
Description copied from interface:Cache
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
public void close()
Description copied from interface:Cache
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()
-
getCacheManager
public CacheManager getCacheManager()
Description copied from interface:Cache
Return the cache manager for this cache instance.- Specified by:
getCacheManager
in interfaceCache<K,V>
-
isClosed
public boolean isClosed()
Description copied from interface:Cache
Returnstrue
if cache was closed or closing is in progress.
-
asMap
public ConcurrentMap<K,V> asMap()
Description copied from interface:Cache
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.
-
requestInterface
public <X> X requestInterface(Class<X> type)
Description copied from interface:Cache
Request an alternative interface for this cache instance.- Specified by:
requestInterface
in interfaceCache<K,V>
-
toString
public String toString()
Description copied from interface:Cache
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.
-
-