Class Cache<K,V>
java.lang.Object
org.glassfish.hk2.utilities.cache.Cache<K,V>
- Type Parameters:
K
- The type of the key of the cacheV
- The type of the values in the cache
- All Implemented Interfaces:
Computable<K,
V>
Cache implementation that relies on FutureTask.
Desired value will only be computed once and computed value stored in the cache.
The implementation is based on an example from the "Java Concurrency in Practice" book
authored by Brian Goetz and company.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interface
Should a cycle be detected during computation of a value for given key, this interface allows client code to register a callback that would get invoked in such a case.private class
Helper class, that remembers the future task origin thread, so that cycles could be detected. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final ConcurrentHashMap
<K, Cache<K, V>.OriginThreadAwareFuture> private final Computable
<K, V> private final Cache.CycleHandler
<K> private static final Cache.CycleHandler
<Object> -
Constructor Summary
ConstructorsConstructorDescriptionCache
(Computable<K, V> computable) Create new cache with given computable to compute values.Cache
(Computable<K, V> computable, Cache.CycleHandler<K> cycleHandler) Create new cache with given computable and cycle handler. -
Method Summary
Modifier and TypeMethodDescriptionvoid
clear()
Empty cache.Defines an expensive computation to retrieve value V from key K.boolean
containsKey
(K key) Returns true if the key has already been cached.void
Remove item from the cache.int
size()
Returns the size of the cache
-
Field Details
-
cycleHandler
-
EMPTY_HANDLER
-
cache
-
computable
-
-
Constructor Details
-
Cache
Create new cache with given computable to compute values. Detected cycles will be ignored as there is a no-op cycle handler registered by default.- Parameters:
computable
-
-
Cache
Create new cache with given computable and cycle handler.- Parameters:
computable
-cycleHandler
-
-
-
Method Details
-
compute
Description copied from interface:Computable
Defines an expensive computation to retrieve value V from key K.- Specified by:
compute
in interfaceComputable<K,
V> - Parameters:
key
- input data.- Returns:
- output from the computation.
-
clear
public void clear()Empty cache. -
containsKey
Returns true if the key has already been cached.- Parameters:
key
-- Returns:
- true if given key is present in the cache.
-
remove
Remove item from the cache.- Parameters:
key
- item key.
-
size
public int size()Returns the size of the cache- Returns:
- The number of elements in the cache
-