K
- Type of the keyV
- Type of the valuepublic class ThreadSafeCache<K,V> extends Object
Instead of storing directly the value in the backing Map, it requires the consumer to provide a value factory (a Callable). A new FutureTask encapsulate the callable, is executed and is placed inside a ConcurrentHashMap if absent.
The final behavior is that, even if two concurrent Threads are borrowing an object from the cache, given that they provide an equivalent value factory, the first one will compute the value while the other will get the result from the Future (and will wait until the result is computed or a timeout occurs).
By default, cache duration is set to 1 minute.
Constructor and Description |
---|
ThreadSafeCache(ScheduledExecutorService executorService)
Build a new
ThreadSafeCache using the given scheduled executor. |
Modifier and Type | Method and Description |
---|---|
void |
clear()
Clean-up the cache entries.
|
V |
getValue(K key,
Callable<V> callable)
Borrow (and create before hand if absent) a cache entry.
|
V |
getValue(K key,
Callable<V> callable,
AsyncFunction<V,Duration,Exception> expire)
Borrow (and create before hand if absent) a cache entry.
|
void |
setDefaultTimeout(Duration defaultTimeout)
Sets the default cache entry expiration delay, if none provided in the
caller.
|
public ThreadSafeCache(ScheduledExecutorService executorService)
ThreadSafeCache
using the given scheduled executor.executorService
- scheduled executor for registering expiration callbacks.public void setDefaultTimeout(Duration defaultTimeout)
defaultTimeout
- new cache entry timeoutpublic V getValue(K key, Callable<V> callable) throws InterruptedException, ExecutionException
key
- entry keycallable
- cached value factoryInterruptedException
- if the current thread was interrupted while waitingExecutionException
- if the cached value computation threw an exceptionpublic V getValue(K key, Callable<V> callable, AsyncFunction<V,Duration,Exception> expire) throws InterruptedException, ExecutionException
key
- entry keycallable
- cached value factoryexpire
- function to override the global cache's timeoutInterruptedException
- if the current thread was interrupted while waitingExecutionException
- if the cached value computation threw an exceptionpublic void clear()
Copyright 2011-2015 ForgeRock AS.