Class Cache<K,V>
- Type Parameters:
K
- the type of key objects.V
- the type of value objects.
- All Implemented Interfaces:
ConcurrentMap<K,
,V> Map<K,
V>
- Direct Known Subclasses:
TileCache
Cache
is based on ConcurrentHashMap
with the addition of three main capabilities:
- Lock an entry when its value is under computation in a thread.
- Block other threads requesting the value of that particular entry until computation is completed.
- Retain oldest values by soft or weak references instead of strong references.
computeIfAbsent(…)
or getOrCreate(…)
with lambda functions as below:
Alternatively, one can handle explicitly the locks.
This alternative sometimes provides more flexibility, for example in exception handling.
The steps are as below:
- Check if the value is already available in the map. If it is, return it immediately and we are done.
- Otherwise, get a lock and check again if the value is already available in the map (because the value could have been computed by another thread between step 1 and the obtention of the lock). If it is, release the lock and we are done.
- Otherwise compute the value, store the result and release the lock.
putAndUnlock(…)
must
be inside the finally
block of a try
block beginning immediately after the call
to lock(…)
, no matter what the result of the computation is (including null
).
Eviction of eldest values
- The cost of a value is the value returned by
cost(V)
. The default implementation returns 1 in all cases, but subclasses can override this method for more elaborated cost computation. - The total cost is the sum of the cost of all values held by strong reference in this cache. The total cost does not include the cost of values held by weak or soft reference.
- The cost limit is the maximal value allowed for the total cost. If the total cost exceed this value, then strong references to the eldest values are replaced by weak or soft references until the total cost become equals or lower than the cost limit.
cost(V)
method has not been
overridden, then the total cost is the maximal amount of values to keep by strong references.
Circular dependencies
This implementation assumes that there are no circular dependencies (or cyclic graph) between the values in the cache. For example if creating A implies creating B, then creating B is not allowed to implies (directly or indirectly) the creation of A. If this condition is not met, deadlock may occur randomly.- Since:
- 0.3
- Version:
- 1.3
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final class
Key-value pairs of new entries created duringCache.ReplaceAdapter
execution, as a chained list.static interface
The handler returned bylock(K)
, to be used for unlocking and storing the result.private final class
A callback formap
which forwards the calls to theremapping
function provided by user.private final class
A simple handler implementation wrapping an existing value.private final class
A soft reference which removes itself from the cache when the reference is garbage-collected.private final class
private final class
A weak reference which removes itself from the cache when the reference is garbage-collected.(package private) final class
A handler implementation used for telling to other threads that the current thread is computing a value.Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,
V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object, V extends Object> -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final long
The maximal cost allowed.The keys of values that are retained in the map by strong references, together with an estimation of their cost.A view over the entries in the cache.private boolean
true
if different values may be assigned to the same key.private final ConcurrentMap<K,
Object> The map that contains the cached values.private final boolean
private long
The sum of all values in thecosts
map. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate void
adjustReferences
(K key, V value) Invoked in a background thread after a value has been set in the map.void
clear()
Clears the content of this cache.Replaces the value mapped to the given key by a new value computed from the old value.computeIfAbsent
(K key, Function<? super K, ? extends V> creator) Returns the value for the given key if it exists, or computes it otherwise.computeIfPresent
(K key, BiFunction<? super K, ? super V, ? extends V> remapping) Replaces the value mapped to the given key by a new value computed from the old value.boolean
containsKey
(Object key) Returnstrue
if this map contains the specified key.protected int
Computes an estimation of the cost of the given value.private static void
ensureValidType
(Object value) Ensures that the given value is not an instance of a reserved type.entrySet()
Returns the set of entries in this cache.boolean
flush()
Forces the removal of all garbage collected values in the map.Returns the value mapped to the given key in the cache, potentially waiting for computation to complete.getOrCreate
(K key, Callable<? extends V> creator) Returns the value for the given key if it exists, or computes it otherwise.private static <V> V
immediateValueOf
(Object value) Returns the value of the given object if it is not under computation.boolean
isEmpty()
Returnstrue
if this cache is empty.boolean
Returnstrue
if different values may be assigned to the same key.private static boolean
Returnstrue
if the given value is null or a cleared reference.private static boolean
isReservedType
(Object value) Returnstrue
if the given value is an instance of one of the reserved types used internally by this class.keySet()
Returns the set of keys in this cache.Gets a lock for the entry at the given key and returns a handler to be used by the caller for unlocking and storing the result.Maps the given value to the given key if no mapping existed before this method call, or computes a new value otherwise.private void
notifyChange
(K key, V value) Notifies thisCache
instance that an entry has changed.If a value is already cached for the given key, returns it.Puts the given value in cache and immediately returns the old value.putIfAbsent
(K key, V value) If no value is already mapped and no value is under computation for the given key, puts the given value in the cache.Removes the value mapped to the given key in the cache.boolean
If the given key is mapped to the given old value, removes that value.private void
Removes the given key from the map if it is associated to the given value, otherwise do nothing.If the given key is mapped to any value, replaces that value with the given new value.boolean
If the given key is mapped to the given old value, replaces that value with the given new value.void
replaceAll
(BiFunction<? super K, ? super V, ? extends V> remapping) Iterates over all entries in the cache and replaces their value with the one provided by the given function.void
setKeyCollisionAllowed
(boolean allowed) If set totrue
, different values may be assigned to the same key.int
size()
Returns the number of elements in this cache.private static <V> V
Returns the value of the given object, unwrapping it if possible.Methods inherited from class java.util.AbstractMap
clone, containsValue, equals, hashCode, putAll, toString, values
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.concurrent.ConcurrentMap
forEach, getOrDefault
-
Field Details
-
map
The map that contains the cached values. If a value is in the process of being computed, then the value is a temporary instance ofCache.Handler
. Otherwise the value is a weak or softReference
objects, or otherwise a strong<V>
reference.- See Also:
-
costs
The keys of values that are retained in the map by strong references, together with an estimation of their cost. This map is not thread safe; it shall be used by a single thread at any given time, even for read-only operations.Entries in this map are ordered from least-recently accessed to most-recently accessed.
-
totalCost
private long totalCost -
costLimit
private final long costLimitThe maximal cost allowed. If thetotalCost
is above that limit, then the eldest strong references will be replaced by weak or soft references. -
soft
private final boolean soft -
isKeyCollisionAllowed
private volatile boolean isKeyCollisionAllowedtrue
if different values may be assigned to the same key. This is usually an error, so the defaultCache
behavior is to throw an exception in such cases.- See Also:
-
entries
A view over the entries in the cache.- See Also:
-
-
Constructor Details
-
Cache
public Cache()Creates a new cache with a default initial capacity and cost limit of 100. The oldest objects will be hold by weak references. -
Cache
public Cache(int initialCapacity, long costLimit, boolean soft) Creates a new cache using the given initial capacity and cost limit. The initial capacity is the expected number of values to be stored in this cache. More values are allowed, but a little bit of CPU time may be saved if the expected capacity is known before the cache is created.The cost limit is the maximal value of the total cost (the sum of the cost of all values) before to replace eldest strong references by weak or soft references.
- Parameters:
initialCapacity
- the initial capacity.costLimit
- the maximum cost of objects to keep by strong reference.soft
- iftrue
, useSoftReference
instead ofWeakReference
.
-
-
Method Details
-
clear
public void clear()Clears the content of this cache. -
isEmpty
public boolean isEmpty()Returnstrue
if this cache is empty. -
size
public int size() -
get
Returns the value mapped to the given key in the cache, potentially waiting for computation to complete. This method is similar topeek(Object)
except that it blocks if the value is currently under computation in another thread. -
getOrCreate
Returns the value for the given key if it exists, or computes it otherwise. If a value already exists in the cache, then it is returned immediately. Otherwise thecreator.call()
method is invoked and its result is saved in this cache for future reuse.Example: the following example shows how this method can be used. In particular, it shows how to propagateThis method is similar toMyCheckedException
:computeIfAbsent(Object, Function)
except that it can propagate checked exceptions. If thecreator
function does not throw any checked exception, then invokingcomputeIfAbsent(…)
is simpler.- Parameters:
key
- the key for which to get the cached or created value.creator
- a method for creating a value, to be invoked only if no value are cached for the given key.- Returns:
- the value for the given key, which may have been created as a result of this method call.
- Throws:
Exception
- if an exception occurred during the execution ofcreator.call()
.- See Also:
-
computeIfAbsent
Returns the value for the given key if it exists, or computes it otherwise. If a value already exists in the cache, then it is returned immediately. Otherwise thecreator.apply(Object)
method is invoked and its result is saved in this cache for future reuse.Example: below is the same code thanThis method is similar togetOrCreate(Object, Callable)
example, but without the need for any checked exception handling:getOrCreate(Object, Callable)
, but without checked exceptions.- Specified by:
computeIfAbsent
in interfaceConcurrentMap<K,
V> - Specified by:
computeIfAbsent
in interfaceMap<K,
V> - Parameters:
key
- the key for which to get the cached or created value.creator
- a method for creating a value, to be invoked only if no value are cached for the given key.- Returns:
- the value already mapped to the key, or the newly computed value.
- Since:
- 1.0
- See Also:
-
isNull
Returnstrue
if the given value is null or a cleared reference.- Parameters:
value
- the value to test.- Returns:
- whether the given value is null or a cleared reference.
-
isReservedType
Returnstrue
if the given value is an instance of one of the reserved types used internally by this class. -
ensureValidType
Ensures that the given value is not an instance of a reserved type.- Throws:
IllegalArgumentException
-
valueOf
Returns the value of the given object, unwrapping it if possible. If the value is under computation in another thread, this method will block until the computation is completed. -
immediateValueOf
Returns the value of the given object if it is not under computation. This method is similar tovalueOf(Object)
except that it does not block if the value is under computation. -
notifyChange
Notifies thisCache
instance that an entry has changed. This method is invoked afterput(…)
,replace(…)
andremove(…)
operations. It does not need to be atomic with above-cited operations because this method performs its work in a background thread anyway. If the value for the specified key was retained by weak reference, it become a value retained by strong reference. Conversely some values previously retained by strong references may be retained by weak references after the cost adjustment performed by this method.- Parameters:
key
- key of the entry that changed.value
- the new value. May benull
.
-
putIfAbsent
If no value is already mapped and no value is under computation for the given key, puts the given value in the cache. Otherwise returns the current value (potentially blocking until the computation finishes). A nullvalue
argument is equivalent to a no-op. Otherwise anull
return value means that the givenvalue
has been stored in theCache
.- Specified by:
putIfAbsent
in interfaceConcurrentMap<K,
V> - Specified by:
putIfAbsent
in interfaceMap<K,
V> - Parameters:
key
- the key to associate with a value.value
- the value to associate with the given key if no value already exists, ornull
.- Returns:
- the existing value mapped to the given key, or
null
if none existed before this method call. - Since:
- 1.0
- See Also:
-
put
Puts the given value in cache and immediately returns the old value. A nullvalue
argument removes the entry. If a different value is under computation in another thread, then the other thread may fail with anIllegalStateException
unlessisKeyCollisionAllowed()
returnstrue
. For more safety, consider usingputIfAbsent(…)
instead.- Specified by:
put
in interfaceMap<K,
V> - Overrides:
put
in classAbstractMap<K,
V> - Parameters:
key
- the key to associate with a value.value
- the value to associate with the given key, ornull
for removing the mapping.- Returns:
- the value previously mapped to the given key, or
null
if no value existed before this method call or if the value was under computation in another thread. - See Also:
-
replace
If the given key is mapped to any value, replaces that value with the given new value. Otherwise does nothing. A nullvalue
argument removes the entry. If a different value is under computation in another thread, then the other thread may fail with anIllegalStateException
unlessisKeyCollisionAllowed()
returnstrue
.- Specified by:
replace
in interfaceConcurrentMap<K,
V> - Specified by:
replace
in interfaceMap<K,
V> - Parameters:
key
- key of the value to replace.value
- the new value to use in replacement of the previous one, ornull
for removing the mapping.- Returns:
- the value previously mapped to the given key, or
null
if no value existed before this method call or if the value was under computation in another thread. - Since:
- 1.0
- See Also:
-
replace
If the given key is mapped to the given old value, replaces that value with the given new value. Otherwise does nothing. A nullvalue
argument removes the entry if the condition matches. If a value is under computation in another thread, then this method unconditionally returnsfalse
.- Specified by:
replace
in interfaceConcurrentMap<K,
V> - Specified by:
replace
in interfaceMap<K,
V> - Parameters:
key
- key of the value to replace.oldValue
- previous value expected to be mapped to the given key.newValue
- the new value to put if the condition matches, ornull
for removing the mapping.- Returns:
true
if the value has been replaced,false
otherwise.- Since:
- 1.0
-
replaceAll
Iterates over all entries in the cache and replaces their value with the one provided by the given function. If the function throws an exception, the iteration is stopped and the exception is propagated. If any value is under computation in other threads, then the iteration will block on that entry until its computation is completed.- Specified by:
replaceAll
in interfaceConcurrentMap<K,
V> - Specified by:
replaceAll
in interfaceMap<K,
V> - Parameters:
remapping
- the function computing new values from the old ones.- Since:
- 1.0
-
computeIfPresent
Replaces the value mapped to the given key by a new value computed from the old value. If a value for the given key is under computation in another thread, then this method blocks until that computation is completed. This is equivalent to the work performed byreplaceAll(…)
but on a single entry.- Specified by:
computeIfPresent
in interfaceConcurrentMap<K,
V> - Specified by:
computeIfPresent
in interfaceMap<K,
V> - Parameters:
key
- key of the value to replace.remapping
- the function computing new values from the old ones.- Returns:
- the new value associated with the given key.
- Since:
- 1.0
- See Also:
-
compute
Replaces the value mapped to the given key by a new value computed from the old value. If there is no value for the given key, then the "old value" is taken asnull
. If a value for the given key is under computation in another thread, then this method blocks until that computation is completed. This method is equivalent tocomputeIfPresent(…)
except that a new value will be computed even if no value existed for the key before this method call.- Specified by:
compute
in interfaceConcurrentMap<K,
V> - Specified by:
compute
in interfaceMap<K,
V> - Parameters:
key
- key of the value to replace.remapping
- the function computing new values from the old ones, or from anull
value.- Returns:
- the new value associated with the given key.
- Since:
- 1.0
- See Also:
-
merge
Maps the given value to the given key if no mapping existed before this method call, or computes a new value otherwise. If a value for the given key is under computation in another thread, then this method blocks until that computation is completed.- Specified by:
merge
in interfaceConcurrentMap<K,
V> - Specified by:
merge
in interfaceMap<K,
V> - Parameters:
key
- key of the value to replace.value
- the value to associate with the given key if no value already exists, ornull
.remapping
- the function computing a new value by merging the exiting value with thevalue
argument given to this method.- Returns:
- the new value associated with the given key.
- Since:
- 1.0
-
remove
Removes the value mapped to the given key in the cache. If a value is under computation in another thread, then the other thread may fail with anIllegalStateException
unlessisKeyCollisionAllowed()
returnstrue
. For more safety, consider usingremove(Object, Object)
instead.- Specified by:
remove
in interfaceMap<K,
V> - Overrides:
remove
in classAbstractMap<K,
V> - Parameters:
key
- the key of the value to removed.- Returns:
- the value previously mapped to the given key, or
null
if no value existed before this method call or if the value was under computation in another thread. - See Also:
-
remove
If the given key is mapped to the given old value, removes that value. Otherwise does nothing. If a value is under computation in another thread, then this method unconditionally returnsfalse
. -
containsKey
Returnstrue
if this map contains the specified key. If the value is under computation in another thread, this method returnstrue
without waiting for the computation result. This behavior is consistent with otherMap
methods in the following ways:get(Object)
blocks until the computation is completed.put(Object, Object)
returnsnull
for values under computation, i.e. behaves as if keys are temporarily mapped to thenull
value until the computation is completed.
- Specified by:
containsKey
in interfaceMap<K,
V> - Overrides:
containsKey
in classAbstractMap<K,
V> - Parameters:
key
- the key to check for existence.- Returns:
true
if the given key is mapped to an existing value or a value under computation.- See Also:
-
peek
If a value is already cached for the given key, returns it. Otherwise returnsnull
. This method is similar toget(Object)
except that it doesn't block if the value is in process of being computed in another thread; it returnsnull
in such case.- Parameters:
key
- the key for which to get the cached value.- Returns:
- the cached value for the given key, or
null
if there is none. - See Also:
-
lock
Gets a lock for the entry at the given key and returns a handler to be used by the caller for unlocking and storing the result. This method must be used together with aputAndUnlock
call intry
…catch
blocks as in the example below:- Parameters:
key
- the key for the entry to lock.- Returns:
- a handler to use for unlocking and storing the result.
-
adjustReferences
Invoked in a background thread after a value has been set in the map. This method computes a cost estimation of the new value. If the total cost is greater than the cost limit, then oldest strong references are replaced by weak references until the cost of entries kept by strong references become lower than the threshold. -
removeKey
Removes the given key from the map if it is associated to the given value, otherwise do nothing. This method is invoked when the value of a weak or soft reference has been cleared. Theoretically no entry for that key should exist in thecosts
map because that map contains only the keys of objects hold by strong references. But we check anyway for reducing the risk of memory leaks. It may happen if some keys are removed fromkeySet()
instead of usingCache
API.- Parameters:
key
- key of the entry to remove.value
- expected value associated to the given entry.
-
keySet
Returns the set of keys in this cache. The returned set is subjects to the same caution than the ones documented in theConcurrentHashMap.keySet()
method.If some elements are removed from the key set, then
flush()
should be invoked after removals. This is not done automatically by the returned set. For safety, theremove(Object)
methods defined in theCache
class should be used instead. -
entrySet
Returns the set of entries in this cache. The returned set is subjects to the same caution than the ones documented in theConcurrentHashMap.entrySet()
method, except that it does not support removal of elements (including through theIterator.remove()
method call). -
isKeyCollisionAllowed
public boolean isKeyCollisionAllowed()Returnstrue
if different values may be assigned to the same key. The default value isfalse
.- Returns:
true
if key collisions are allowed.
-
setKeyCollisionAllowed
public void setKeyCollisionAllowed(boolean allowed) If set totrue
, different values may be assigned to the same key. This is usually an error, so the defaultCache
behavior is to thrown anIllegalStateException
in such cases, typically whenCache.Handler.putAndUnlock(Object)
is invoked. However, in some cases we may want to relax this check. For example, the EPSG database sometimes assigns the same key to different kinds of objects.If key collisions are allowed and two threads invoke
lock(Object)
concurrently for the same key, then the value to be stored in the map will be the one computed by the first thread who got the lock. The value computed by any other concurrent thread will be ignored by thisCache
class. However, those threads still return their computed values to their callers.This property can also be set in order to allow some recursivity. If during the creation of an object, the program asks to this
Cache
for the same object (using the same key), then the defaultCache
implementation will consider this situation as a key collision unless this property has been set totrue
.- Parameters:
allowed
-true
if key collisions should be allowed.
-
cost
Computes an estimation of the cost of the given value. The default implementation returns 1 in all cases. Subclasses should override this method if they have some easy way to measure the relative cost of value objects.- Parameters:
value
- the object for which to get an estimation of its cost.- Returns:
- the estimated cost of the given object.
- See Also:
-
flush
public boolean flush()Forces the removal of all garbage collected values in the map. This method should not need to be invoked when usingCache
API. It is provided as a debugging tools when suspecting a memory leak.- Returns:
true
if some entries have been removed as a result of this method call.- Since:
- 1.3
- See Also:
-