K - The Key typeV - The Value typepublic class Cache<K,V> extends Object implements Thread.UncaughtExceptionHandler, ActionContext<K,V>
// Build native TCache instance Builder<String, Integer> builder = TCacheFactory.standardFactory().builder(); builder.setXYZ(value); Cache<String, Integer> cache = builder.build(); javax.cache.Cache<String, Integer> jsr107cache = tcache.jsr107cache();The last line above is optional, to get a JSR107 compliant Cache instance. Alternatively that could also be created via the JSR107 API:
// Build JSR107 Cache instance
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration<String, Integer> config = new MutableConfiguration<>()
.setXYZ(value); // Configure
javax.cache.Cache<String, Integer> cache = cacheManager.createCache("simpleCache", config); // Build
Implementation note: This Cache class is built for maximum throughput and scalability, by executing CPU intensive tasks like evictions in separate Threads. The basic limitations are those of the underlying ConcurrentMap implementation, as no further data structures are maintained. This is also true for the subclasses that allow evictions.
| Modifier and Type | Class and Description |
|---|---|
class |
Cache.CleanupThread
Thread that removes expired entries.
|
| Modifier and Type | Field and Description |
|---|---|
protected JamPolicy |
jamPolicy |
protected javax.cache.integration.CacheLoader<K,V> |
loader |
protected ConcurrentMap<K,AccessTimeObjectHolder<V>> |
objects |
| Constructor and Description |
|---|
Cache(TCacheFactory factory,
Builder<K,V> builder)
Construct a Cache, using the given configuration from the Builder.
|
| Modifier and Type | Method and Description |
|---|---|
protected TimeSource |
activateTimeSource()
Returns the TimeSource for this Cache.
|
javax.cache.integration.CacheWriter<K,V> |
cacheWriter() |
void |
clear()
Removes all entries from the Cache without notifying Listeners
|
void |
close()
Closes the cache and removes it from the associated CacheManager.
|
protected String |
configToString() |
TriavaCacheConfiguration<K,V,? extends Builder<K,V>> |
configuration() |
boolean |
containsKey(K key)
Returns true if this Cache contains a mapping for the specified key.
|
void |
enableManagement(boolean enable) |
void |
enableStatistics(boolean enable)
Enables or disables statistics.
|
protected boolean |
ensureFreeCapacity()
Returns whether there is capacity for at least one more element.
|
protected int |
evictionExtraSpace(Builder<K,V> builder)
Returns a size factor for the map for the specific eviction strategy of this Cache.
|
void |
expireUntil(K key,
int maxDelay,
TimeUnit timeUnit)
Schedule the entry for the given key for expiration.
|
protected TCacheStatisticsInterface |
fillCacheStatistics(TCacheStatisticsInterface cacheStatistic)
Fills the given cache statistics object.
|
protected AccessTimeObjectHolder<V> |
gatedHolder(AccessTimeObjectHolder<V> holder) |
V |
get(K key)
Gets cached object for the given key, or null if this Cache contains no mapping for the key.
|
V |
getAndPut(K key,
V value)
Add an object to the cache under the given key, using the default idle time and default cache time.
|
V |
getAndReplace(K key,
V value)
Replace the entry stored by key with the given value.
|
float |
getCacheHitrate()
Returns the Cache hit rate.
|
String |
id() |
boolean |
isClosed() |
boolean |
isManagementEnabled() |
boolean |
isStatisticsEnabled() |
TCacheHolderIterator<K,V> |
iterator()
Returns an Iterator which can be used to traverse all entries of the Cache.
|
TCacheHolderIterator<K,V> |
iteratorWithTouch()
Returns an Iterator which can be used to traverse all entries of the Cache.
|
boolean |
joinSimple(Thread thread,
long millis,
int nanos)
Waits at most millis milliseconds plus nanos nanoseconds for the given thread to die.
|
TCacheJSR107<K,V> |
jsr107cache()
Returns a JSR107 compliant view on this Cache.
|
Collection<K> |
keySet()
Returns a thread-safe unmodifiable collection of the keys.
|
ListenerCollection<K,V> |
listeners() |
void |
put(K key,
V value)
Add an object to the cache under the given key, using the default idle time and default cache time.
|
void |
put(K key,
V value,
int idleTime,
int cacheTime,
TimeUnit timeUnit)
Add an object to the cache under the given key with the given idle and cache times.
|
V |
putIfAbsent(K key,
V value)
The same like
putIfAbsent(Object, Object, int, int, TimeUnit), but uses
the default idle and cache times. |
V |
putIfAbsent(K key,
V value,
int idleTime,
int cacheTime,
TimeUnit timeUnit)
The same like
put(Object, Object, int, int, TimeUnit), but uses
ConcurrentMap.putIfAbsent(Object, Object) to actually write
the data in the backing ConcurrentMap. |
protected AccessTimeObjectHolder<V> |
putToMap(K key,
V data,
long idleTime,
long cacheTime,
boolean putIfAbsent,
boolean returnEffectiveHolder)
Puts the value wrapped in a AccessTimeObjectHolder in the map and returns it.
|
V |
remove(K key)
Removes the mapping for the given key, and returns the value that was stored for it.
|
boolean |
remove(K key,
V value)
Removes the object with given key, if stored in the Cache.
|
protected V |
removeAndRelease(K key)
Removes the mapping for the given key, and releases the associated holder.
|
ChangeStatus |
replace(K key,
V oldValue,
V newValue) |
CacheSizeInfo |
reportSize(ObjectSizeCalculatorInterface objectSizeCalculator)
Measures the number of elements and the size of this Cache in bytes and logs it.
|
static void |
setLogger(TriavaLogger logger)
Sets the logger that will be used for all Cache instances.
|
int |
size() |
TCacheStatistics |
statistics() |
StatisticsCalculator |
statisticsCalculator() |
protected String |
stopAndClear(long millis) |
String |
toString() |
void |
uncaughtException(Thread thread,
Throwable throwable)
This is called, if the CleanupThread goes down on an unexpected (uncaught) Exception.
|
protected final ConcurrentMap<K,AccessTimeObjectHolder<V>> objects
protected final JamPolicy jamPolicy
public Cache(TCacheFactory factory, Builder<K,V> builder)
builder - The builder containing the configurationfactory - The factory, in which this Cache will be registered.protected int evictionExtraSpace(Builder<K,V> builder)
builder - The builder containing the configurationpublic String id()
public final void close()
public boolean isClosed()
public boolean joinSimple(Thread thread, long millis, int nanos)
thread - The target threadmillis - The number of milliseconds to waitnanos - The number of nanoseconds to waitpublic void put(K key, V value)
key - The keyvalue - The valuepublic V getAndPut(K key, V value)
key - The keyvalue - The valuepublic void put(K key, V value, int idleTime, int cacheTime, TimeUnit timeUnit)
key - The keyvalue - The valueidleTime - The idle time in secondscacheTime - The cache time in secondstimeUnit - The TimeUnit for both idleTime and cacheTimepublic V putIfAbsent(K key, V value, int idleTime, int cacheTime, TimeUnit timeUnit)
put(Object, Object, int, int, TimeUnit), but uses
ConcurrentMap.putIfAbsent(Object, Object) to actually write
the data in the backing ConcurrentMap. For the sake of the Cache hit or miss statistics this method
is a treated as a read operation and thus updates the hit or miss counters. Rationale is that the
putIfAbsent() result is usually evaluated by the caller.key - The keyvalue - The valueidleTime - Maximum idle time in secondscacheTime - Maximum cache time in secondstimeUnit - The TimeUnit for both idleTime and cacheTimeConcurrentHashMap.putIfAbsent(Object, Object)public V putIfAbsent(K key, V value)
putIfAbsent(Object, Object, int, int, TimeUnit), but uses
the default idle and cache times. The cache time will use the cache time spread if this cache
is configured to use it.key - The keyvalue - The valueConcurrentHashMap.putIfAbsent(Object, Object)protected AccessTimeObjectHolder<V> putToMap(K key, V data, long idleTime, long cacheTime, boolean putIfAbsent, boolean returnEffectiveHolder)
ConcurrentMap.putIfAbsent(Object, Object), otherwise
like Map.put(Object, Object).key - The keydata - The valueidleTime - in millisecondscacheTime - Max Cache time in millisecondsputIfAbsent - Defines the behavior when the key is already present. See method documentation.returnEffectiveHolder - If true, the holder object of the object in the Map is returned. If returnEffectiveHolder is false, the returned value is like described in Map.put(Object, Object).protected AccessTimeObjectHolder<V> gatedHolder(AccessTimeObjectHolder<V> holder)
public V getAndReplace(K key, V value)
key - The keyvalue - The value to writeCache.getAndReplace(Object, Object)public ChangeStatus replace(K key, V oldValue, V newValue)
protected boolean ensureFreeCapacity()
public V get(K key) throws RuntimeException
key - The keyRuntimeException - if key is not present and the loader threw an Exception.NullPointerException - if key is null.protected TCacheStatisticsInterface fillCacheStatistics(TCacheStatisticsInterface cacheStatistic)
cacheStatistic - The statistics object to fillpublic TCacheStatistics statistics()
public float getCacheHitrate()
public void clear()
protected String stopAndClear(long millis)
protected TimeSource activateTimeSource()
public void uncaughtException(Thread thread, Throwable throwable)
uncaughtException in interface Thread.UncaughtExceptionHandlerpublic int size()
public boolean remove(K key, V value)
key - The keyvalue - The valuepublic V remove(K key)
Implementation note: The return value reflects the "remove-from-map" outcome, not the "release". This is to fulfill the JSR Spec and TCK. In the future it should be checked again whether we can make it reflect the "release" again, as it would be cleaner (i.e.: atomic, more consistent)
key - The keyprotected V removeAndRelease(K key)
Implementation note: The return value reflects the "release" outcome, not the removal from the Map. This is done, as the "release" operation is a GATE, and it can only be passed once per Holder.
key - The keypublic void expireUntil(K key, int maxDelay, TimeUnit timeUnit)
0, the entry is set to expire immediately.
This method is especially useful if many cache entries are to be invalidated, and fetching data is an expensive operation. As each call to this method will chose a different expiration time, expiration and thus possible re-fetching will spread over a longer time, and helps to avoid resource overload (like DB, REST Service, ...).
key - The key for the entry to expiremaxDelay - The maximum delay time until the object will be expiredtimeUnit - The time unit for maxDelayIllegalArgumentException - - if the maxDelay value is < 0public TCacheHolderIterator<K,V> iterator()
WARNING!!! Up to v0.9.9, the value reflects the actual state and may change after retrieving. For example accessTime can change if the entry is accessed, and value.get() may return null if it is expired. This behavior will change with v1.0, and the returned value will we immutable.
public TCacheHolderIterator<K,V> iteratorWithTouch()
iterator(), but the traversed elements are
treated as touched. This means, access time is updated and hit count statistics are maintained.
WARNING!!! Up to v0.9.9, the value reflects the actual state and may change after retrieving. For example accessTime can change if the entry is accessed, and value.get() may return null if it is expired. This behavior will change with v1.0, and the returned value will we immutable.
public Collection<K> keySet()
public boolean containsKey(K key)
key - The keyMap.containsKey(Object)public static void setLogger(TriavaLogger logger)
logger - The logger to usepublic CacheSizeInfo reportSize(ObjectSizeCalculatorInterface objectSizeCalculator)
objectSizeCalculator - The implementation to usepublic TCacheJSR107<K,V> jsr107cache()
public void enableStatistics(boolean enable)
statistics() and also
by JSR107 compliant MXBeans. Disabling statistics will discard all statistics.enable - true for enabling statistics.public void enableManagement(boolean enable)
public boolean isStatisticsEnabled()
public boolean isManagementEnabled()
public javax.cache.integration.CacheWriter<K,V> cacheWriter()
cacheWriter in interface ActionContext<K,V>public ListenerCollection<K,V> listeners()
listeners in interface ActionContext<K,V>public StatisticsCalculator statisticsCalculator()
statisticsCalculator in interface ActionContext<K,V>protected String configToString()
Copyright © 2018 trivago. All rights reserved.