Class Cache
- java.lang.Object
-
- net.sf.ehcache.Cache
-
- All Implemented Interfaces:
java.lang.Cloneable,java.util.EventListener,Ehcache,StoreListener,InternalEhcache
public class Cache extends java.lang.Object implements InternalEhcache, StoreListener
Cache is the central class in ehcache. Caches haveElements and are managed by theCacheManager. The Cache performs logical actions. It delegates physical implementations to itsStores.A reference to a Cache can be obtained through the
CacheManager. A Cache thus obtained is guaranteed to have statusStatus.STATUS_ALIVE. This status is checked for any method which throwsIllegalStateExceptionand the same thrown if it is not alive. This would normally happen if a call is made afterCacheManager.shutdown()is invoked.Cache is threadsafe.
Statistics on cache usage are collected and made available through the
getStatistics()methods.Various decorators are available for Cache, such as BlockingCache, SelfPopulatingCache and the dynamic proxy ExceptionHandlingDynamicCacheProxy. See each class for details.
- Version:
- $Id$
- Author:
- Greg Luck, Geert Bevin
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.StringDEFAULT_CACHE_NAMEA reserved word for cache names.static longDEFAULT_EXPIRY_THREAD_INTERVAL_SECONDSThe default interval between runs of the expiry thread.static java.lang.StringNET_SF_EHCACHE_DISABLEDSystem Property based method of disabling ehcache.static java.lang.StringNET_SF_EHCACHE_USE_CLASSIC_LRUSystem Property based method of selecting the LruMemoryStore in use up to ehcache 1.5.
-
Constructor Summary
Constructors Constructor Description Cache(java.lang.String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds)1.0 Constructor.Cache(java.lang.String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds)1.1 Constructor.Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners)1.2 ConstructorCache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader)1.2.1 ConstructorCache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk)1.2.4 ConstructorCache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB)1.3 ConstructorCache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB, boolean clearOnFlush)1.6.0 ConstructorCache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB, boolean clearOnFlush, boolean isTerracottaClustered, boolean terracottaCoherentReads)1.7.0 ConstructorCache(CacheConfiguration cacheConfiguration)2.0 and higher ConstructorCache(CacheConfiguration cacheConfiguration, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader)2.0 and higher Constructor
-
Method Summary
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidacquireReadLockOnKey(java.lang.Object key)Acquires the proper read lock for a given cache keyvoidacquireWriteLockOnKey(java.lang.Object key)Acquires the proper write lock for a given cache keyvoidaddPropertyChangeListener(java.beans.PropertyChangeListener listener)Add a PropertyChangeListener.voidbootstrap()Bootstrap command.longcalculateInMemorySize()Deprecated.longcalculateOffHeapSize()Deprecated.longcalculateOnDiskSize()Deprecated.Cacheclone()Clones a cache.voidclusterCoherent(boolean clusterCoherent)Inform of cluster coherence.protected DiskStorecreateDiskStore()Creates a disk store when either: overflowToDisk is enabled diskPersistent is enabledQuerycreateQuery()Create a new query builder for this cachevoiddisableDynamicFeatures()Disables dynamic configuration and disable/enable for this cache.voiddispose()Starts an orderly shutdown of the Cache.booleanequals(java.lang.Object object)An equals method which follows the contract ofObject.equals(Object)voidevictExpiredElements()Causes all elements stored in the Cache to be synchronously checked for expiry, and if expired, evicted.voidfirePropertyChange(java.lang.String propertyName, java.lang.Object oldValue, java.lang.Object newValue)voidflush()Flushes all cache items from memory to the disk store, and from the DiskStore to disk.Elementget(java.io.Serializable key)Gets an element from the cache.Elementget(java.lang.Object key)Gets an element from the cache.java.util.Map<java.lang.Object,Element>getAll(java.util.Collection<?> keys)Gets all the elements from the cache for the keys provided.java.util.MapgetAllWithLoader(java.util.Collection keys, java.lang.Object loaderArgument)The getAll method will return, from the cache, a Map of the objects associated with the Collection of keys in argument "keys".BootstrapCacheLoadergetBootstrapCacheLoader()Accessor for the BootstrapCacheLoader associated with this cache.CacheConfigurationgetCacheConfiguration()Gets the cache configuration this cache was created with.RegisteredEventListenersgetCacheEventNotificationService()Use this to access the service in order to register and unregister listenersCacheExceptionHandlergetCacheExceptionHandler()Gets the ExceptionHandler on this Cache, or null if there isn't one.CacheManagergetCacheManager()Gets the CacheManager managing this cache.intgetDiskStoreSize()Deprecated.java.lang.StringgetGuid()The GUID for this cache instance can be used to determine whether two cache instance references are pointing to the same cache.java.lang.ObjectgetInternalContext()This should not be usedjava.util.ListgetKeys()Returns a list of all element keys in the cache, whether or not they are expired.java.util.ListgetKeysNoDuplicateCheck()Returns a list of all elements in the cache, whether or not they are expired.java.util.ListgetKeysWithExpiryCheck()Returns a list of all element keys in the cache.protected SyncgetLockForKey(java.lang.Object key)Gets the lock for a given keyPolicygetMemoryStoreEvictionPolicy()longgetMemoryStoreSize()Deprecated.java.lang.StringgetName()Gets the cache name.longgetOffHeapStoreSize()Deprecated.ElementgetQuiet(java.io.Serializable key)Gets an element from the cache, without updating Element statistics.ElementgetQuiet(java.lang.Object key)Gets an element from the cache, without updating Element statistics.java.util.List<CacheExtension>getRegisteredCacheExtensions()java.util.List<CacheLoader>getRegisteredCacheLoaders()CacheWritergetRegisteredCacheWriter()Retrieves theCacheWriterthat was registered for this cache.<T> Attribute<T>getSearchAttribute(java.lang.String attributeName)Retrieve the given named search attributejava.util.Set<Attribute>getSearchAttributes()intgetSize()Gets the size of the cache.StatisticsGatewaygetStatistics()Gets an immutable Statistics object representing the Cache statistics at the time.StatusgetStatus()Gets the status attribute of the Cache.java.lang.ObjectgetStoreMBean()Get the optional store management bean for this cache.TransactionManagerLookupgetTransactionManagerLookup()Get the TransactionManagerLookup implementation used to lookup the TransactionManager.ElementgetWithLoader(java.lang.Object key, CacheLoader loader, java.lang.Object loaderArgument)This method will return, from the cache, the Element associated with the argument "key".CacheWriterManagergetWriterManager()Obtain the writer manager that's used by this cache instance.booleanhasAbortedSizeOf()Check if the cache may contain elements which the SizeOf engine could not fully size.inthashCode()Returns a hash code value for the object.voidinitialise()Newly created caches do not have aStore.booleanisClusterBulkLoadEnabled()Returns true if at least one node in the cluster is in bulk-load mode.booleanisClusterCoherent()Deprecated.useisClusterBulkLoadEnabled()insteadbooleanisDisabled()Whether this cache is disabled.protected booleanisDiskStore()Whether this cache uses a disk storebooleanisElementInMemory(java.io.Serializable key)Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.booleanisElementInMemory(java.lang.Object key)Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.booleanisElementOffHeap(java.lang.Object key)Whether an Element is stored in the cache in off-heap memory, indicating an intermediate cost of retrieval.booleanisElementOnDisk(java.io.Serializable key)Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.booleanisElementOnDisk(java.lang.Object key)Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.booleanisExpired(Element element)Checks whether this cache element has expired.booleanisKeyInCache(java.lang.Object key)An inexpensive check to see if the key exists in the cache.booleanisNodeBulkLoadEnabled()Returns true if the current node is in bulk-load mode.booleanisNodeCoherent()Deprecated.useisNodeBulkLoadEnabled()insteadbooleanisReadLockedByCurrentThread(java.lang.Object key)Returns true if a read lock for the key is held by the current threadbooleanisSearchable()Is this cache searchable?booleanisTerracottaClustered()Indicates whether this cache is clustered by TerracottabooleanisValueInCache(java.lang.Object value)An extremely expensive check to see if the value exists in the cache.booleanisWriteLockedByCurrentThread(java.lang.Object key)Returns true if a write lock for the key is held by the current threadvoidload(java.lang.Object key)The load method provides a means to "pre-load" the cache.voidloadAll(java.util.Collection keys, java.lang.Object argument)The loadAll method provides a means to "pre load" objects into the cache.voidput(Element element)Put an element in the cache.voidput(Element element, boolean doNotNotifyCacheReplicators)Put an element in the cache.voidputAll(java.util.Collection<Element> elements)Puts a collection of elements in to the cache.ElementputIfAbsent(Element element)Put an element in the cache if no element is currently mapped to the elements key.ElementputIfAbsent(Element element, boolean doNotNotifyCacheReplicators)Put an element in the cache if no element is currently mapped to the elements key.voidputQuiet(Element element)Put an element in the cache, without updating statistics, or updating listeners.voidputWithWriter(Element element)Put an element in the cache writing through a CacheWriter.voidrecalculateSize(java.lang.Object key)Recalculate the size of the element mapped to the keyvoidregisterCacheExtension(CacheExtension cacheExtension)Register aCacheExtensionwith the cache.voidregisterCacheLoader(CacheLoader cacheLoader)Register aCacheLoaderwith the cache.voidregisterCacheWriter(CacheWriter cacheWriter)Register theCacheWriterfor this cache.voidregisterDynamicAttributesExtractor(DynamicAttributesExtractor extractor)Allows user to register a dynamic attribute extractor with a searchable cache that is dynamically indexable, as indicated by its configuration.voidreleaseReadLockOnKey(java.lang.Object key)Release a held read lock for the passed in keyvoidreleaseWriteLockOnKey(java.lang.Object key)Release a held write lock for the passed in keybooleanremove(java.io.Serializable key)Removes anElementfrom the Cache.booleanremove(java.io.Serializable key, boolean doNotNotifyCacheReplicators)Removes anElementfrom the Cache.booleanremove(java.lang.Object key)Removes anElementfrom the Cache.booleanremove(java.lang.Object key, boolean doNotNotifyCacheReplicators)Removes anElementfrom the Cache.voidremoveAll()Removes all cached items.voidremoveAll(boolean doNotNotifyCacheReplicators)Removes all cached items.voidremoveAll(java.util.Collection<?> keys)Removes given set ofElementfrom the Cache.voidremoveAll(java.util.Collection<?> keys, boolean doNotNotifyCacheReplicators)Removes all cached items.ElementremoveAndReturnElement(java.lang.Object key)Removes anElementfrom the Cache and returns it.booleanremoveElement(Element element)Remove the Element mapped to the key for the supplied element if the value of the supplied Element compares equal to the value of the cached Element.voidremovePropertyChangeListener(java.beans.PropertyChangeListener listener)Remove a PropertyChangeListener.booleanremoveQuiet(java.io.Serializable key)Removes anElementfrom the Cache, without notifying listeners.booleanremoveQuiet(java.lang.Object key)Removes anElementfrom the Cache, without notifying listeners.booleanremoveWithWriter(java.lang.Object key)Removes anElementfrom the Cache and any stores it might be in.Elementreplace(Element element)Replace the cached element only if an Element is currently cached for this keybooleanreplace(Element old, Element element)Replace the cached element only if the current Element is equal to the supplied old Element.voidsetBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader)Sets the bootstrap cache loader.voidsetCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler)Sets an ExceptionHandler on the Cache.voidsetCacheManager(CacheManager cacheManager)For use by CacheManager.voidsetDisabled(boolean disabled)Disables or enables this cache.voidsetMemoryStoreEvictionPolicy(Policy policy)Sets the eviction policy strategy.voidsetName(java.lang.String name)Sets the cache name which will name.voidsetNodeBulkLoadEnabled(boolean enabledBulkLoad)Enable/disable bulk-load mode in this node for this cache.voidsetNodeCoherent(boolean coherent)Deprecated.usesetNodeBulkLoadEnabled(boolean)insteadvoidsetTransactionManagerLookup(TransactionManagerLookup lookup)Sets the TransactionManagerLookup that needs to be used for this cache to lookup the TransactionManager This needs to be set beforeinitialise()is calledjava.lang.StringtoString()Returns aStringrepresentation ofCache.booleantryReadLockOnKey(java.lang.Object key, long timeout)Try to get a read lock on a given key.booleantryWriteLockOnKey(java.lang.Object key, long timeout)Try to get a write lock on a given key.voidunregisterCacheExtension(CacheExtension cacheExtension)Unregister aCacheExtensionwith the cache.voidunregisterCacheLoader(CacheLoader cacheLoader)Unregister aCacheLoaderwith the cache.voidunregisterCacheWriter()Unregister theCacheWriterfrom the cache.voidwaitUntilClusterBulkLoadComplete()This method waits until all the connected nodes have disabled bulk-load.voidwaitUntilClusterCoherent()Deprecated.usewaitUntilClusterBulkLoadComplete()instead
-
-
-
Field Detail
-
DEFAULT_CACHE_NAME
public static final java.lang.String DEFAULT_CACHE_NAME
A reserved word for cache names. It denotes a default configuration which is applied to caches created without configuration.- See Also:
- Constant Field Values
-
NET_SF_EHCACHE_DISABLED
public static final java.lang.String NET_SF_EHCACHE_DISABLED
System Property based method of disabling ehcache. If disabled no elements will be added to a cache.Set the property "net.sf.ehcache.disabled=true" to disable ehcache.
This can easily be done using
java -Dnet.sf.ehcache.disabled=truein the command line.- See Also:
- Constant Field Values
-
NET_SF_EHCACHE_USE_CLASSIC_LRU
public static final java.lang.String NET_SF_EHCACHE_USE_CLASSIC_LRU
System Property based method of selecting the LruMemoryStore in use up to ehcache 1.5. This is provided for ease of migration.Set the property "net.sf.ehcache.use.classic.lru=true" to use the older LruMemoryStore implementation when LRU is selected as the eviction policy.
This can easily be done using
java -Dnet.sf.ehcache.use.classic.lru=truein the command line.- See Also:
- Constant Field Values
-
DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS
public static final long DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS
The default interval between runs of the expiry thread.
-
-
Constructor Detail
-
Cache
public Cache(CacheConfiguration cacheConfiguration)
2.0 and higher ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
cacheConfiguration- the configuration that should be used to create the cache with
-
Cache
public Cache(CacheConfiguration cacheConfiguration, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader)
2.0 and higher ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
cacheConfiguration- the configuration that should be used to create the cache withregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds)1.0 Constructor.The
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
This constructor creates disk stores, if specified, that do not persist between restarts.
The default expiry thread interval of 120 seconds is used. This is the interval between runs of the expiry thread, where it checks the disk store for expired elements. It is not the the timeToLiveSeconds.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)overflowToDisk- whether to use the disk storeeternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified date- Since:
- 1.0
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds)1.1 Constructor.The
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)overflowToDisk- whether to use the disk storeeternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended- Since:
- 1.1
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners)1.2 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.- Since:
- 1.2
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader)1.2.1 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.- Since:
- 1.2.1
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk)1.2.4 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.maxElementsOnDisk- the maximum number of Elements to allow on the disk. 0 means unlimited.- Since:
- 1.2.4
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB)1.3 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.maxElementsOnDisk- the maximum number of Elements to allow on the disk. 0 means unlimited.diskSpoolBufferSizeMB- the amount of memory to allocate the write buffer for puts to the DiskStore.- Since:
- 1.3
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB, boolean clearOnFlush)1.6.0 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.maxElementsOnDisk- the maximum number of Elements to allow on the disk. 0 means unlimited.diskSpoolBufferSizeMB- the amount of memory to allocate the write buffer for puts to the DiskStore.clearOnFlush- whether the in-memory storage should be cleared whenflush()is called on the cache- Since:
- 1.6.0
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
Cache
public Cache(java.lang.String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk, java.lang.String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners, BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB, boolean clearOnFlush, boolean isTerracottaClustered, boolean terracottaCoherentReads)1.7.0 ConstructorThe
ConfigurationFactoryand clients can create these.A client can specify their own settings here and pass the
Cacheobject intoCacheManager.addCache(java.lang.String)to specify parameters other than the defaults.Only the CacheManager can initialise them.
- Parameters:
name- the name of the cache. Note that "default" is a reserved name for the defaultCache.maxElementsInMemory- the maximum number of elements in memory, before they are evicted (0 == no limit)memoryStoreEvictionPolicy- one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.overflowToDisk- whether to use the disk storediskStorePath- this parameter is ignored. CacheManager sets it using setter injection.eternal- whether the elements in the cache are eternal, i.e. never expiretimeToLiveSeconds- the default amount of time to live for an element from its creation datetimeToIdleSeconds- the default amount of time to live for an element from its last accessed or modified datediskPersistent- whether to persist the cache to disk between JVM restartsdiskExpiryThreadIntervalSeconds- how often to run the disk store expiry thread. A large number of 120 seconds plus is recommendedregisteredEventListeners- a notification service. Optionally null, in which case a new one with no registered listeners will be created.bootstrapCacheLoader- the BootstrapCacheLoader to use to populate the cache when it is first initialised. Null if none is required.maxElementsOnDisk- the maximum number of Elements to allow on the disk. 0 means unlimited.diskSpoolBufferSizeMB- the amount of memory to allocate the write buffer for puts to the DiskStore.clearOnFlush- whether the in-memory storage should be cleared whenflush()is called on the cacheisTerracottaClustered- whether to cluster this cache with TerracottaterracottaCoherentReads- whether this cache should use coherent reads (usually should be true) unless optimizing for read-only- Since:
- 1.7.0
- See Also:
Cache(CacheConfiguration, RegisteredEventListeners, BootstrapCacheLoader), for full construction support of version 2.0 and higher features.
-
-
Method Detail
-
getTransactionManagerLookup
public TransactionManagerLookup getTransactionManagerLookup()
Get the TransactionManagerLookup implementation used to lookup the TransactionManager. This is generally only set for XA transactional caches- Returns:
- The
TransactionManagerLookupinstance
-
setTransactionManagerLookup
public void setTransactionManagerLookup(TransactionManagerLookup lookup)
Sets the TransactionManagerLookup that needs to be used for this cache to lookup the TransactionManager This needs to be set beforeinitialise()is called- Specified by:
setTransactionManagerLookupin interfaceEhcache- Parameters:
lookup- TheTransactionManagerLookupinstance
-
initialise
public void initialise()
Newly created caches do not have aStore.This method creates the store and makes the cache ready to accept elements
- Specified by:
initialisein interfaceEhcache
-
getWriterManager
public CacheWriterManager getWriterManager()
Obtain the writer manager that's used by this cache instance.- Specified by:
getWriterManagerin interfaceEhcache- Returns:
- the writer manager that's set up for this cache
-
createDiskStore
protected DiskStore createDiskStore()
Creates a disk store when either:- overflowToDisk is enabled
- diskPersistent is enabled
- Returns:
- the disk store
-
isDiskStore
protected boolean isDiskStore()
Whether this cache uses a disk store- Returns:
- true if the cache either overflows to disk or uses a local-classic persistence strategy.
-
isTerracottaClustered
public boolean isTerracottaClustered()
Indicates whether this cache is clustered by Terracotta- Returns:
truewhen the cache is clustered by Terracotta; orfalseotherwise
-
bootstrap
public void bootstrap()
Bootstrap command. This must be called after the Cache is initialised, during CacheManager initialisation. If loads are synchronous, they will complete before the CacheManager initialise completes, otherwise they will happen in the background.
-
put
public final void put(Element element) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException, CacheException
Put an element in the cache.Resets the access statistics on the element, which would be the case if it has previously been gotten from a cache, and is now being put back.
Also notifies the CacheEventListener that:
- the element was put, but only if the Element was actually put.
- if the element exists in the cache, that an update has occurred, even if the element would be expired if it was requested
- Specified by:
putin interfaceEhcache- Parameters:
element- A cache Element. If Serializable it can fully participate in replication and the DiskStore. If it isnullor the key isnull, it is ignored as a NOOP.- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- in case of errorjava.lang.IllegalArgumentException- if the element is null
-
putAll
public void putAll(java.util.Collection<Element> elements) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException, CacheException
Puts a collection of elements in to the cache.This method will throw a
NullPointerExceptionif a null element or null key is encountered in the collection, and a partial completion may result (as only some of the elements may have been put).For each element that is put the registered
CacheEventListeners are notified of a newly put item (notifyElementPut(...)) regardless of whether the individual put is a new put or an update.- Specified by:
putAllin interfaceEhcache- Parameters:
elements- the collection of elements to be put in the cache.- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- a runtime cache exceptionjava.lang.IllegalArgumentException
-
put
public final void put(Element element, boolean doNotNotifyCacheReplicators) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException, CacheException
Put an element in the cache.Resets the access statistics on the element, which would be the case if it has previously been gotten from a cache, and is now being put back.
Also notifies the CacheEventListener that:
- the element was put, but only if the Element was actually put.
- if the element exists in the cache, that an update has occurred, even if the element would be expired if it was requested
- Specified by:
putin interfaceEhcache- Parameters:
element- A cache Element. If Serializable it can fully participate in replication and the DiskStore. If it isnullor the key isnull, it is ignored as a NOOP.doNotNotifyCacheReplicators- whether the put is coming from a doNotNotifyCacheReplicators cache peer, in which case this put should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVEjava.lang.IllegalArgumentException- if the element is nullCacheException
-
putWithWriter
public void putWithWriter(Element element) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException, CacheException
Put an element in the cache writing through a CacheWriter. If no CacheWriter has been registered for the cache, then this method throws an exception.Resets the access statistics on the element, which would be the case if it has previously been gotten from a cache, and is now being put back.
Also notifies the CacheEventListener, if the writer operation succeeds, that:
- the element was put, but only if the Element was actually put.
- if the element exists in the cache, that an update has occurred, even if the element would be expired if it was requested
- Specified by:
putWithWriterin interfaceEhcache- Parameters:
element- An object. If Serializable it can fully participate in replication and the DiskStore.- Throws:
java.lang.IllegalArgumentException- if the element is nulljava.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- if no CacheWriter was registered
-
putQuiet
public final void putQuiet(Element element) throws java.lang.IllegalArgumentException, java.lang.IllegalStateException, CacheException
Put an element in the cache, without updating statistics, or updating listeners. This is meant to be used in conjunction withgetQuiet(java.io.Serializable). Synchronization is handled within the method.Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
putQuietin interfaceEhcache- Parameters:
element- A cache Element. If Serializable it can fully participate in replication and the DiskStore. If it isnullor the key isnull, it is ignored as a NOOP.- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVEjava.lang.IllegalArgumentException- if the element is nullCacheException
-
get
public final Element get(java.io.Serializable key) throws java.lang.IllegalStateException, CacheException
Gets an element from the cache. Updates Element StatisticsNote that the Element's lastAccessTime is always the time of this get. Use
getQuiet(Object)to peak into the Element to see its last access time with getSynchronization is handled within the method.
- Specified by:
getin interfaceEhcache- Parameters:
key- a serializable value. Null keys are not stored so get(null) always returns null- Returns:
- the element, or null, if it does not exist.
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- See Also:
isExpired(net.sf.ehcache.Element)
-
get
public final Element get(java.lang.Object key) throws java.lang.IllegalStateException, CacheException
Gets an element from the cache. Updates Element StatisticsNote that the Element's lastAccessTime is always the time of this get. Use
getQuiet(Object)to peak into the Element to see its last access time with getSynchronization is handled within the method.
- Specified by:
getin interfaceEhcache- Parameters:
key- an Object value- Returns:
- the element, or null, if it does not exist.
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- Since:
- 1.2
- See Also:
isExpired(net.sf.ehcache.Element)
-
getAll
public java.util.Map<java.lang.Object,Element> getAll(java.util.Collection<?> keys) throws java.lang.IllegalStateException, CacheException
Gets all the elements from the cache for the keys provided. Updates Element Statistics Throws a NullPointerException if any key in the collection is nullNote that the Element's lastAccessTime is always the time of this get. Use
Ehcache.getQuiet(Object)to peek into the Element to see its last access time with get- Specified by:
getAllin interfaceEhcache- Parameters:
keys- a collection of keys for which value is to be fetched- Returns:
- Map of key and elements for the provided keys, value will be null for the keys which do not exist
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- See Also:
Ehcache.isExpired(net.sf.ehcache.Element)
-
getWithLoader
public Element getWithLoader(java.lang.Object key, CacheLoader loader, java.lang.Object loaderArgument) throws CacheException
This method will return, from the cache, the Element associated with the argument "key".If the Element is not in the cache, the associated cache loader will be called. That is either the CacheLoader passed in, or if null, the one associated with the cache. If both are null, no load is performed and null is returned.
Because this method may take a long time to complete, it is not synchronized. The underlying cache operations are synchronized.
- Specified by:
getWithLoaderin interfaceEhcache- Parameters:
key- key whose associated value is to be returned.loader- the override loader to use. If null, the cache's default loader will be usedloaderArgument- an argument to pass to the CacheLoader.- Returns:
- an element if it existed or could be loaded, otherwise null
- Throws:
CacheException- if the loading fails
-
load
public void load(java.lang.Object key) throws CacheExceptionThe load method provides a means to "pre-load" the cache. This method will, asynchronously, load the specified object into the cache using the associated CacheLoader. If the object already exists in the cache, no action is taken. If no loader is associated with the object, no object will be loaded into the cache. If a problem is encountered during the retrieving or loading of the object, an exception should be logged. If the "arg" argument is set, the arg object will be passed to the CacheLoader.load method. The cache will not dereference the object. If no "arg" value is provided a null will be passed to the load method. The storing of null values in the cache is permitted, however, the get method will not distinguish returning a null stored in the cache and not finding the object in the cache. In both cases a null is returned.The Ehcache native API provides similar functionality to loaders using the decorator
SelfPopulatingCache- Specified by:
loadin interfaceEhcache- Parameters:
key- key whose associated value to be loaded using the associated CacheLoader if this cache doesn't contain it.- Throws:
CacheException- in case of error
-
getAllWithLoader
public java.util.Map getAllWithLoader(java.util.Collection keys, java.lang.Object loaderArgument) throws CacheExceptionThe getAll method will return, from the cache, a Map of the objects associated with the Collection of keys in argument "keys". If the objects are not in the cache, the associated cache loader will be called. If no loader is associated with an object, a null is returned. If a problem is encountered during the retrieving or loading of the objects, an exception will be thrown. If the "arg" argument is set, the arg object will be passed to the CacheLoader.loadAll method. The cache will not dereference the object. If no "arg" value is provided a null will be passed to the loadAll method. The storing of null values in the cache is permitted, however, the get method will not distinguish returning a null stored in the cache and not finding the object in the cache. In both cases a null is returned.Note. If the getAll exceeds the maximum cache size, the returned map will necessarily be less than the number specified.
Because this method may take a long time to complete, it is not synchronized. The underlying cache operations are synchronized.
The constructs package provides similar functionality using the decorator
SelfPopulatingCache- Specified by:
getAllWithLoaderin interfaceEhcache- Parameters:
keys- a collection of keys to be returned/loadedloaderArgument- an argument to pass to the CacheLoader.- Returns:
- a Map populated from the Cache. If there are no elements, an empty Map is returned.
- Throws:
CacheException- in case of error
-
loadAll
public void loadAll(java.util.Collection keys, java.lang.Object argument) throws CacheExceptionThe loadAll method provides a means to "pre load" objects into the cache. This method will, asynchronously, load the specified objects into the cache using the associated cache loader(s). If the an object already exists in the cache, no action is taken. If no loader is associated with the object, no object will be loaded into the cache. If a problem is encountered during the retrieving or loading of the objects, an exception (to be defined) should be logged. The getAll method will return, from the cache, a Map of the objects associated with the Collection of keys in argument "keys". If the objects are not in the cache, the associated cache loader will be called. If no loader is associated with an object, a null is returned. If a problem is encountered during the retrieving or loading of the objects, an exception (to be defined) will be thrown. If the "arg" argument is set, the arg object will be passed to the CacheLoader.loadAll method. The cache will not dereference the object. If no "arg" value is provided a null will be passed to the loadAll method.keys - collection of the keys whose associated values to be loaded into this cache by using the associated CacheLoader if this cache doesn't contain them.
The Ehcache native API provides similar functionality to loaders using the decorator
SelfPopulatingCache- Specified by:
loadAllin interfaceEhcache- Parameters:
keys- - collection of the keys whose associated values to be loaded into this cache by using the associated cacheloader if this cache doesn't contain them.argument- can be anything that makes sense to the loaderThe Ehcache native API provides similar functionality to loaders using the decorator
SelfPopulatingCache- Throws:
CacheException
-
getQuiet
public final Element getQuiet(java.io.Serializable key) throws java.lang.IllegalStateException, CacheException
Gets an element from the cache, without updating Element statistics. Cache statistics are still updated. Listeners are not called.- Specified by:
getQuietin interfaceEhcache- Parameters:
key- a serializable value- Returns:
- the element, or null, if it does not exist.
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- See Also:
isExpired(net.sf.ehcache.Element)
-
getQuiet
public final Element getQuiet(java.lang.Object key) throws java.lang.IllegalStateException, CacheException
Gets an element from the cache, without updating Element statistics. Cache statistics are not updated.Listeners are not called.
- Specified by:
getQuietin interfaceEhcache- Parameters:
key- a serializable value- Returns:
- the element, or null, if it does not exist.
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- Since:
- 1.2
- See Also:
isExpired(net.sf.ehcache.Element)
-
getKeys
public final java.util.List getKeys() throws java.lang.IllegalStateException, CacheExceptionReturns a list of all element keys in the cache, whether or not they are expired.The returned keys are unique and can almost be considered a set. See
CacheKeySetfor more details.The List returned is not live. It is a copy.
The time taken is O(n). For large caches - or caches with high-latency storage this method can take a very long time to complete, may cause timeouts if using features such NonStopCache or transactions, and is not guaranteed to give a consistent view of the cache entry set. Usage is highly discouraged.
- Specified by:
getKeysin interfaceEhcache- Returns:
- a list of
Objectkeys - Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException- See Also:
CacheKeySet
-
getKeysWithExpiryCheck
public final java.util.List getKeysWithExpiryCheck() throws java.lang.IllegalStateException, CacheExceptionReturns a list of all element keys in the cache. Only keys of non-expired elements are returned.The returned keys are unique and can be considered a set.
The List returned is not live. It is a copy.
The time taken is O(n), where n is the number of elements in the cache. On a 1.8Ghz P4, the time taken is approximately 200ms per 1000 entries. This method is not synchronized, because it relies on a non-live list returned from
getKeys(), which is synchronised, and which takes 8ms per 1000 entries. This way cache liveness is preserved, even if this method is very slow to return.Consider whether your usage requires checking for expired keys. Because this method takes so long, depending on cache settings, the list could be quite out of date by the time you get it.
- Specified by:
getKeysWithExpiryCheckin interfaceEhcache- Returns:
- a list of
Objectkeys - Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
getKeysNoDuplicateCheck
public final java.util.List getKeysNoDuplicateCheck() throws java.lang.IllegalStateExceptionReturns a list of all elements in the cache, whether or not they are expired.The returned keys are not unique and may contain duplicates. If the cache is only using the memory store, the list will be unique. If the disk store is being used as well, it will likely contain duplicates, because of the internal store design.
The List returned is not live. It is a copy.
The time taken is O(log n). On a single CPU 1.8Ghz P4, approximately 6ms is required for 1000 entries and 36 for 50000.
This is the fastest getKeys method
- Specified by:
getKeysNoDuplicateCheckin interfaceEhcache- Returns:
- a list of
Objectkeys - Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
remove
public final boolean remove(java.io.Serializable key) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache. This also removes it from any stores it may be in.Also notifies the CacheEventListener after the element was removed.
Synchronization is handled within the method.
Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removein interfaceEhcache- Parameters:
key- the element key to operate on- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
remove
public final boolean remove(java.lang.Object key) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache. This also removes it from any stores it may be in.Also notifies the CacheEventListener after the element was removed, but only if an Element with the key actually existed.
Synchronization is handled within the method.
Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removein interfaceEhcache- Parameters:
key- the element key to operate on- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE- Since:
- 1.2
-
removeAndReturnElement
public final Element removeAndReturnElement(java.lang.Object key) throws java.lang.IllegalStateException
Removes anElementfrom the Cache and returns it. This also removes it from any stores it may be in.Also notifies the CacheEventListener after the element was removed, but only if an Element with the key actually existed.
Synchronization is handled within the method.
Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removeAndReturnElementin interfaceInternalEhcache- Parameters:
key- the element key to operate on- Returns:
- element the removed element associated with the key, null if no mapping exists
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
removeAll
public void removeAll(java.util.Collection<?> keys) throws java.lang.IllegalStateExceptionRemoves given set ofElementfrom the Cache. This also removes them from any stores it may be in. Throws a NullPointerException if any key in the collection is nullAlso notifies the CacheEventListener after the elements were removed. Notification is sent for every key irrespective of whether the key was present in the cache or not This operation is partially completed if any element or any key is null
- Specified by:
removeAllin interfaceEhcache- Parameters:
keys- a collection of keys to operate on- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
removeAll
public final void removeAll(java.util.Collection<?> keys, boolean doNotNotifyCacheReplicators) throws java.lang.IllegalStateExceptionRemoves all cached items.When using Terracotta clustered caches with nonstop enabled, the timeout used by this method is
NonstopConfiguration.getBulkOpsTimeoutMultiplyFactor()times the timeout value in the nonstop config.- Specified by:
removeAllin interfaceEhcache- Parameters:
keys- a collection of keys to operate ondoNotNotifyCacheReplicators- whether the put is coming from a doNotNotifyCacheReplicators cache peer, in which case this put should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
remove
public final boolean remove(java.io.Serializable key, boolean doNotNotifyCacheReplicators) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache. This also removes it from any stores it may be in.Also notifies the CacheEventListener after the element was removed, but only if an Element with the key actually existed.
Synchronization is handled within the method.
Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removein interfaceEhcache- Parameters:
key- the element key to operate ondoNotNotifyCacheReplicators- whether the remove is coming from a doNotNotifyCacheReplicators cache peer, in which case this remove should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
remove
public final boolean remove(java.lang.Object key, boolean doNotNotifyCacheReplicators) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache. This also removes it from any stores it may be in.Also notifies the CacheEventListener after the element was removed, but only if an Element with the key actually existed.
Synchronization is handled within the method.
- Specified by:
removein interfaceEhcache- Parameters:
key- the element key to operate ondoNotNotifyCacheReplicators- whether the remove is coming from a doNotNotifyCacheReplicators cache peer, in which case this remove should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
removeQuiet
public final boolean removeQuiet(java.io.Serializable key) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache, without notifying listeners. This also removes it from any stores it may be in.Listeners are not called.
- Specified by:
removeQuietin interfaceEhcache- Parameters:
key- the element key to operate on- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
removeQuiet
public final boolean removeQuiet(java.lang.Object key) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache, without notifying listeners. This also removes it from any stores it may be in.Listeners are not called.
Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removeQuietin interfaceEhcache- Parameters:
key- the element key to operate on- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE- Since:
- 1.2
-
removeWithWriter
public boolean removeWithWriter(java.lang.Object key) throws java.lang.IllegalStateExceptionRemoves anElementfrom the Cache and any stores it might be in. This also removes through to a CacheWriter. If no CacheWriter has been registered for the cache, then this method throws an exception.Also notifies the CacheEventListener after the element was removed, but only if an Element with the key actually existed.
- Specified by:
removeWithWriterin interfaceEhcache- Parameters:
key- of the element to remove- Returns:
- true if the element was removed, false if it was not found in the cache
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
removeAll
public void removeAll() throws java.lang.IllegalStateException, CacheExceptionRemoves all cached items. Terracotta clustered caches may require more time to execute this operation because cached items must also be removed from the Terracotta Server Array. Synchronization is handled within the method.Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removeAllin interfaceEhcache- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
removeAll
public void removeAll(boolean doNotNotifyCacheReplicators) throws java.lang.IllegalStateException, CacheExceptionRemoves all cached items. Synchronization is handled within the method.Caches which use synchronous replication can throw RemoteCacheException here if the replication to the cluster fails. This exception should be caught in those circumstances.
- Specified by:
removeAllin interfaceEhcache- Parameters:
doNotNotifyCacheReplicators- whether the put is coming from a doNotNotifyCacheReplicators cache peer, in which case this put should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
dispose
public void dispose() throws java.lang.IllegalStateExceptionStarts an orderly shutdown of the Cache. Steps are:- Completes any outstanding CacheLoader loads.
- Completes any outstanding CacheWriter operations.
- Disposes any cache extensions.
- Disposes any cache event listeners. The listeners normally complete, so for example distributed caching operations will complete.
- Flushes all cache items from memory to the disk store, if any
- changes status to shutdown, so that any cache operations after this point throw IllegalStateException
- Specified by:
disposein interfaceEhcache- Throws:
java.lang.IllegalStateException- if the cache is alreadyStatus.STATUS_SHUTDOWN
-
getCacheConfiguration
public CacheConfiguration getCacheConfiguration()
Gets the cache configuration this cache was created with.Things like listeners that are added dynamically are excluded.
- Specified by:
getCacheConfigurationin interfaceEhcache- Returns:
- CacheConfiguration the cache configuration
-
flush
public final void flush() throws java.lang.IllegalStateException, CacheExceptionFlushes all cache items from memory to the disk store, and from the DiskStore to disk.- Specified by:
flushin interfaceEhcache- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
getSize
public final int getSize() throws java.lang.IllegalStateException, CacheExceptionGets the size of the cache. This is a subtle concept. See below.This number is the actual number of elements, including expired elements that have not been removed.
Expired elements are removed from the the memory store when getting an expired element, or when attempting to spool an expired element to disk.
Expired elements are removed from the disk store when getting an expired element, or when the expiry thread runs, which is once every five minutes.
To get an exact size, which would exclude expired elements, use
getKeysWithExpiryCheck().size(), although see that method for the approximate time that would take.To get a very fast result, use
getKeysNoDuplicateCheck().size(). If the disk store is being used, there will be some duplicates.Note:getSize() is a very expensive operation in off-heap, disk and Terracotta implementations.
- Specified by:
getSizein interfaceEhcache- Returns:
- The size value
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
calculateInMemorySize
@Deprecated public final long calculateInMemorySize() throws java.lang.IllegalStateException, CacheExceptionDeprecated.Gets the size of the memory store for this cache. This method relies on calculating Serialized sizes. If the Element values are not Serializable they will show as zero.Warning: This method can be very expensive to run. Allow approximately 1 second per 1MB of entries. Running this method could create liveness problems because the object lock is held for a long period
- Specified by:
calculateInMemorySizein interfaceEhcache- Returns:
- the approximate size of the memory store in bytes
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
hasAbortedSizeOf
public boolean hasAbortedSizeOf()
Check if the cache may contain elements which the SizeOf engine could not fully size.- Specified by:
hasAbortedSizeOfin interfaceEhcache- Returns:
- true if the cache may contain partially sized objects
-
calculateOffHeapSize
@Deprecated public final long calculateOffHeapSize() throws java.lang.IllegalStateException, CacheExceptionDeprecated.Gets the size of the off-heap store for this cache.- Specified by:
calculateOffHeapSizein interfaceEhcache- Returns:
- the size of the off-heap store in bytes
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
calculateOnDiskSize
@Deprecated public final long calculateOnDiskSize() throws java.lang.IllegalStateException, CacheExceptionDeprecated.Gets the size of the on-disk store for this cache- Specified by:
calculateOnDiskSizein interfaceEhcache- Returns:
- the size of the on-disk store in bytes
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVECacheException
-
getMemoryStoreSize
@Deprecated public final long getMemoryStoreSize() throws java.lang.IllegalStateExceptionDeprecated.Returns the number of elements in the memory store.- Specified by:
getMemoryStoreSizein interfaceEhcache- Returns:
- the number of elements in the memory store
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
getOffHeapStoreSize
@Deprecated public long getOffHeapStoreSize() throws java.lang.IllegalStateExceptionDeprecated.Returns the number of elements in the off-heap store.- Specified by:
getOffHeapStoreSizein interfaceEhcache- Returns:
- the number of elements in the off-heap store
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
getDiskStoreSize
@Deprecated public final int getDiskStoreSize() throws java.lang.IllegalStateExceptionDeprecated.Returns the number of elements in the disk store.- Specified by:
getDiskStoreSizein interfaceEhcache- Returns:
- the number of elements in the disk store.
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
getStatus
public final Status getStatus()
Gets the status attribute of the Cache.
-
getName
public final java.lang.String getName()
Gets the cache name.
-
setName
public final void setName(java.lang.String name) throws java.lang.IllegalArgumentExceptionSets the cache name which will name.
-
toString
public java.lang.String toString()
Returns aStringrepresentation ofCache.
-
isExpired
public final boolean isExpired(Element element) throws java.lang.IllegalStateException, java.lang.NullPointerException
Checks whether this cache element has expired.The element is expired if:
- the idle time is non-zero and has elapsed, unless the cache is eternal; or
- the time to live is non-zero and has elapsed, unless the cache is eternal; or
- the value of the element is null.
- Specified by:
isExpiredin interfaceEhcache- Parameters:
element- the element to check- Returns:
- true if it has expired
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVEjava.lang.NullPointerException- if the element is null todo this does not need to be synchronized
-
clone
public final Cache clone() throws java.lang.CloneNotSupportedException
Clones a cache. This is only legal if the cache has not been initialized. At that point only primitives have been set and no stores have been created.A new, empty, RegisteredEventListeners is created on clone.
-
getStoreMBean
public final java.lang.Object getStoreMBean()
Get the optional store management bean for this cache.- Returns:
- the store MBean
-
getCacheEventNotificationService
public final RegisteredEventListeners getCacheEventNotificationService()
Use this to access the service in order to register and unregister listeners- Specified by:
getCacheEventNotificationServicein interfaceEhcache- Returns:
- the RegisteredEventListeners instance for this cache.
-
isElementInMemory
public final boolean isElementInMemory(java.io.Serializable key)
Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Specified by:
isElementInMemoryin interfaceEhcache- Parameters:
key- the key of the element to remove- Returns:
- true if an element matching the key is found in memory
-
isElementInMemory
public final boolean isElementInMemory(java.lang.Object key)
Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Specified by:
isElementInMemoryin interfaceEhcache- Parameters:
key- the key of the element to remove- Returns:
- true if an element matching the key is found in memory
- Since:
- 1.2
-
isElementOffHeap
public final boolean isElementOffHeap(java.lang.Object key)
Whether an Element is stored in the cache in off-heap memory, indicating an intermediate cost of retrieval.Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Parameters:
key- key to look for- Returns:
- true if an element matching the key is found in off-heap
- Since:
- 2.3
-
isElementOnDisk
public final boolean isElementOnDisk(java.io.Serializable key)
Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Specified by:
isElementOnDiskin interfaceEhcache- Parameters:
key- key to look for- Returns:
- true if an element matching the key is found in the diskStore
-
isElementOnDisk
public final boolean isElementOnDisk(java.lang.Object key)
Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Specified by:
isElementOnDiskin interfaceEhcache- Parameters:
key- key to look for- Returns:
- true if an element matching the key is found in the diskStore
- Since:
- 1.2
-
getGuid
public final java.lang.String getGuid()
The GUID for this cache instance can be used to determine whether two cache instance references are pointing to the same cache.
-
getCacheManager
public final CacheManager getCacheManager()
Gets the CacheManager managing this cache. For a newly created cache this will be null until it has been added to a CacheManager.- Specified by:
getCacheManagerin interfaceEhcache- Returns:
- the manager or null if there is none
-
evictExpiredElements
public void evictExpiredElements()
Causes all elements stored in the Cache to be synchronously checked for expiry, and if expired, evicted.- Specified by:
evictExpiredElementsin interfaceEhcache
-
isKeyInCache
public boolean isKeyInCache(java.lang.Object key)
An inexpensive check to see if the key exists in the cache.This method is not synchronized. It is possible that an element may exist in the cache and be removed before the check gets to it, or vice versa. Since no assertions are made about the state of the Element it is possible that the Element is expired, but this method still returns true.
- Specified by:
isKeyInCachein interfaceEhcache- Parameters:
key- the key to check.- Returns:
- true if an Element matching the key is found in the cache. No assertions are made about the state of the Element.
-
isValueInCache
public boolean isValueInCache(java.lang.Object value)
An extremely expensive check to see if the value exists in the cache. This implementation is O(n). Ehcache is not designed for efficient access in this manner.This method is not synchronized. It is possible that an element may exist in the cache and be removed before the check gets to it, or vice versa. Because it is slow to execute the probability of that this will have happened.
- Specified by:
isValueInCachein interfaceEhcache- Parameters:
value- to check for- Returns:
- true if an Element matching the key is found in the cache. No assertions are made about the state of the Element.
-
getStatistics
public StatisticsGateway getStatistics() throws java.lang.IllegalStateException
Gets an immutable Statistics object representing the Cache statistics at the time.Note, the
getSize()method will have the same value as the size reported by Statistics for the statistics accuracy of- Specified by:
getStatisticsin interfaceEhcache- Returns:
- the statistics gateway
- Throws:
java.lang.IllegalStateException- if the cache is notStatus.STATUS_ALIVE
-
setCacheManager
public void setCacheManager(CacheManager cacheManager)
For use by CacheManager.- Specified by:
setCacheManagerin interfaceEhcache- Parameters:
cacheManager- the CacheManager for this cache to use.
-
getBootstrapCacheLoader
public BootstrapCacheLoader getBootstrapCacheLoader()
Accessor for the BootstrapCacheLoader associated with this cache. For testing purposes.- Specified by:
getBootstrapCacheLoaderin interfaceEhcache- Returns:
- the BootstrapCacheLoader to use
-
setBootstrapCacheLoader
public void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader) throws CacheException
Sets the bootstrap cache loader.- Specified by:
setBootstrapCacheLoaderin interfaceEhcache- Parameters:
bootstrapCacheLoader- the loader to be used- Throws:
CacheException- if this method is called after the cache is initialized
-
equals
public boolean equals(java.lang.Object object)
An equals method which follows the contract ofObject.equals(Object)An Cache is equal to another one if it implements Ehcache and has the same GUID.
- Overrides:
equalsin classjava.lang.Object- Parameters:
object- the reference object with which to compare.- Returns:
trueif this object is the same as the obj argument;falseotherwise.- See Also:
hashCode(),Hashtable
-
hashCode
public int hashCode()
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided byjava.util.Hashtable.The general contract of
hashCodeis:- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(Object)
method, then calling the
hashCodemethod on each of the two objects must produce the same integer result. - It is not required that if two objects are unequal
according to the
Object.equals(Object)method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java(TM) programming language.)
This implementation use the GUID of the cache.
- Overrides:
hashCodein classjava.lang.Object- Returns:
- a hash code value for this object.
- See Also:
Object.equals(Object),Hashtable
-
registerCacheExtension
public void registerCacheExtension(CacheExtension cacheExtension)
Register aCacheExtensionwith the cache. It will then be tied into the cache lifecycle.If the CacheExtension is not initialised, initialise it.
- Specified by:
registerCacheExtensionin interfaceEhcache- Parameters:
cacheExtension- the cache extension
-
getRegisteredCacheExtensions
public java.util.List<CacheExtension> getRegisteredCacheExtensions()
- Specified by:
getRegisteredCacheExtensionsin interfaceEhcache- Returns:
- the cache extensions as a live list
-
unregisterCacheExtension
public void unregisterCacheExtension(CacheExtension cacheExtension)
Unregister aCacheExtensionwith the cache. It will then be detached from the cache lifecycle.- Specified by:
unregisterCacheExtensionin interfaceEhcache- Parameters:
cacheExtension- the cache extension
-
setCacheExceptionHandler
public void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler)
Sets an ExceptionHandler on the Cache. If one is already set, it is overwritten.The ExceptionHandler is only used if this Cache's methods are accessed using
ExceptionHandlingDynamicCacheProxy.- Specified by:
setCacheExceptionHandlerin interfaceEhcache- Parameters:
cacheExceptionHandler- the cache exception handler- See Also:
ExceptionHandlingDynamicCacheProxy
-
getCacheExceptionHandler
public CacheExceptionHandler getCacheExceptionHandler()
Gets the ExceptionHandler on this Cache, or null if there isn't one.The ExceptionHandler is only used if this Cache's methods are accessed using
ExceptionHandlingDynamicCacheProxy.- Specified by:
getCacheExceptionHandlerin interfaceEhcache- Returns:
- an ExceptionHandler on the Cache
- See Also:
ExceptionHandlingDynamicCacheProxy
-
registerCacheLoader
public void registerCacheLoader(CacheLoader cacheLoader)
Register aCacheLoaderwith the cache. It will then be tied into the cache lifecycle.The CacheLoader instance will be initialized when the cache itself is being initialized. Should the cache already be initialized,
CacheLoader.init()will not be invoked. If the loader requires initialization, the user will have to call it manually before registering it with a Cache instance that's already alive- Specified by:
registerCacheLoaderin interfaceEhcache- Parameters:
cacheLoader- A Cache Loader to register
-
unregisterCacheLoader
public void unregisterCacheLoader(CacheLoader cacheLoader)
Unregister aCacheLoaderwith the cache. It will then be detached from the cache lifecycle.- Specified by:
unregisterCacheLoaderin interfaceEhcache- Parameters:
cacheLoader- A Cache Loader to unregister
-
getRegisteredCacheLoaders
public java.util.List<CacheLoader> getRegisteredCacheLoaders()
- Specified by:
getRegisteredCacheLoadersin interfaceEhcache- Returns:
- the cache loaders as a live list
-
registerCacheWriter
public void registerCacheWriter(CacheWriter cacheWriter)
Register theCacheWriterfor this cache. It will then be tied into the cache lifecycle.If the
CacheWriteris not initialised, initialise it.- Specified by:
registerCacheWriterin interfaceEhcache- Parameters:
cacheWriter- A CacheWriter to register
-
unregisterCacheWriter
public void unregisterCacheWriter()
Unregister theCacheWriterfrom the cache. It will then be detached from the cache lifecycle.If not
CacheWriterwas registered beforehand this operation has no effect.- Specified by:
unregisterCacheWriterin interfaceEhcache
-
getRegisteredCacheWriter
public CacheWriter getRegisteredCacheWriter()
Retrieves theCacheWriterthat was registered for this cache.- Specified by:
getRegisteredCacheWriterin interfaceEhcache- Returns:
- the registered
CacheWriter; ornullif none was registered before
-
registerDynamicAttributesExtractor
public void registerDynamicAttributesExtractor(DynamicAttributesExtractor extractor)
Allows user to register a dynamic attribute extractor with a searchable cache that is dynamically indexable, as indicated by its configuration. Calling this method on such a cache is optional, but doing so more than once replaces previously registered extractor with the given one; i.e., there can be at most one extractor instance configured for each such cache. If the cache was not configured for dynamic indexing, an exception will be thrown- Specified by:
registerDynamicAttributesExtractorin interfaceEhcache- Parameters:
extractor- the dynamic attribute extractor
-
isDisabled
public boolean isDisabled()
Whether this cache is disabled. "Disabled" means:- bootstrap is disabled
- puts are discarded
- putQuiets are discarded
- gets return null
You can disable and enable a cache programmatically through the
setDisabled(boolean)method.By default caches are enabled on creation, unless the
net.sf.ehcache.disabledsystem property is set.- Specified by:
isDisabledin interfaceEhcache- Returns:
- true if the cache is disabled.
- See Also:
?
-
setDisabled
public void setDisabled(boolean disabled)
Disables or enables this cache. This call overrides the previous value of disabled, even if thenet.sf.ehcache.disabledsystem property is set- Specified by:
setDisabledin interfaceEhcache- Parameters:
disabled- true if you wish to disable, false to enable- See Also:
isDisabled()
-
getMemoryStoreEvictionPolicy
public Policy getMemoryStoreEvictionPolicy()
- Returns:
- the current in-memory eviction policy. This may not be the configured policy, if it has been dynamically set.
-
setMemoryStoreEvictionPolicy
public void setMemoryStoreEvictionPolicy(Policy policy)
Sets the eviction policy strategy. The Cache will use a policy at startup. There are three policies which can be configured: LRU, LFU and FIFO. However many other policies are possible. That the policy has access to the whole element enables policies based on the key, value, metadata, statistics, or a combination of any of the above. It is safe to change the policy of a store at any time. The new policy takes effect immediately.- Parameters:
policy- the new policy
-
getInternalContext
public java.lang.Object getInternalContext()
This should not be used- Specified by:
getInternalContextin interfaceEhcache- Returns:
- some internal context (generally will be null)
-
disableDynamicFeatures
public void disableDynamicFeatures()
Disables dynamic configuration and disable/enable for this cache.This is a one time operation. Once an Ehcache instance has had its dynamic operations disabled they cannot be re-enabled.
- Specified by:
disableDynamicFeaturesin interfaceEhcache
-
isClusterCoherent
@Deprecated public boolean isClusterCoherent()
Deprecated.useisClusterBulkLoadEnabled()insteadReturns true if the cache is in coherent mode cluster-wide. Returns false otherwise.It applies to coherent clustering mechanisms only e.g. Terracotta
- Specified by:
isClusterCoherentin interfaceEhcache- Returns:
- true if the cache is in coherent mode cluster-wide, false otherwise
-
isNodeCoherent
@Deprecated public boolean isNodeCoherent()
Deprecated.useisNodeBulkLoadEnabled()insteadReturns true if the cache is in coherent mode for the current node. Returns false otherwise.It applies to coherent clustering mechanisms only e.g. Terracotta
- Specified by:
isNodeCoherentin interfaceEhcache- Returns:
- true if the cache is in coherent mode cluster-wide, false otherwise
-
setNodeCoherent
@Deprecated public void setNodeCoherent(boolean coherent)
Deprecated.usesetNodeBulkLoadEnabled(boolean)insteadSets the cache in coherent or incoherent mode depending on the parameter on this node. CallingsetNodeCoherent(true)when the cache is already in coherent mode or callingsetNodeCoherent(false)when already in incoherent mode will be a no-op.It applies to coherent clustering mechanisms only e.g. Terracotta
When using Terracotta clustered caches with nonstop enabled, the timeout used by this method is
NonstopConfiguration.getBulkOpsTimeoutMultiplyFactor()times the timeout value in the config.- Specified by:
setNodeCoherentin interfaceEhcache- Parameters:
coherent- true transitions to coherent mode, false to incoherent mode
-
waitUntilClusterCoherent
@Deprecated public void waitUntilClusterCoherent()
Deprecated.usewaitUntilClusterBulkLoadComplete()insteadThis method waits until the cache is in coherent mode in all the connected nodes. If the cache is already in coherent mode it returns immediatelyIt applies to coherent clustering mechanisms only e.g. Terracotta
- Specified by:
waitUntilClusterCoherentin interfaceEhcache
-
addPropertyChangeListener
public void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
Description copied from interface:EhcacheAdd a PropertyChangeListener.- Specified by:
addPropertyChangeListenerin interfaceEhcache- Parameters:
listener- thePropertyChangeListenerto add
-
removePropertyChangeListener
public void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
Description copied from interface:EhcacheRemove a PropertyChangeListener.- Specified by:
removePropertyChangeListenerin interfaceEhcache- Parameters:
listener- thePropertyChangeListenerto remove
-
firePropertyChange
public void firePropertyChange(java.lang.String propertyName, java.lang.Object oldValue, java.lang.Object newValue)- Parameters:
propertyName- the name of the property that changedoldValue- the old value of the property that changednewValue- the new value of the property that changed
-
putIfAbsent
public Element putIfAbsent(Element element) throws java.lang.NullPointerException
Put an element in the cache if no element is currently mapped to the elements key.- Specified by:
putIfAbsentin interfaceEhcache- Parameters:
element- element to be added- Returns:
- the element previously cached for this key, or null if none.
- Throws:
java.lang.NullPointerException- if the element is null, or has a null key
-
putIfAbsent
public Element putIfAbsent(Element element, boolean doNotNotifyCacheReplicators) throws java.lang.NullPointerException
Put an element in the cache if no element is currently mapped to the elements key.- Specified by:
putIfAbsentin interfaceEhcache- Parameters:
element- element to be addeddoNotNotifyCacheReplicators- whether the put is coming from a doNotNotifyCacheReplicators cache peer, in which case this put should not initiate a further notification to doNotNotifyCacheReplicators cache peers- Returns:
- the element previously cached for this key, or null if none.
- Throws:
java.lang.NullPointerException- if the element is null, or has a null key
-
removeElement
public boolean removeElement(Element element) throws java.lang.NullPointerException
Remove the Element mapped to the key for the supplied element if the value of the supplied Element compares equal to the value of the cached Element.This is equivalent to
if (elementValueComparator.equals(cache.get(element.getObjectKey()), element)) { return cache.remove(element.getObjectKey()); } else return false;except that the action is performed atomically.- Specified by:
removeElementin interfaceEhcache- Parameters:
element- Element to be removed- Returns:
trueif the value was removed- Throws:
java.lang.NullPointerException- if the element is null, or has a null key- See Also:
CacheConfiguration.addElementValueComparator(net.sf.ehcache.config.ElementValueComparatorConfiguration)
-
replace
public boolean replace(Element old, Element element) throws java.lang.NullPointerException, java.lang.IllegalArgumentException
Replace the cached element only if the current Element is equal to the supplied old Element.- Specified by:
replacein interfaceEhcache- Parameters:
old- Element to be test againstelement- Element to be cached- Returns:
- true if the Element was replaced
- Throws:
java.lang.NullPointerException- if the either Element is null or has a null keyjava.lang.IllegalArgumentException- if the two Element keys are non-null but not equal
-
replace
public Element replace(Element element) throws java.lang.NullPointerException
Replace the cached element only if an Element is currently cached for this key
-
clusterCoherent
public void clusterCoherent(boolean clusterCoherent)
Inform of cluster coherence.- Specified by:
clusterCoherentin interfaceStoreListener- Parameters:
clusterCoherent- if the cluster is coherent- See Also:
StoreListener.clusterCoherent(boolean)
-
getSearchAttributes
public java.util.Set<Attribute> getSearchAttributes() throws CacheException
- Specified by:
getSearchAttributesin interfaceEhcache- Returns:
- set of all search attributes in effect at the time of calling this method
- Throws:
CacheException- in case of error
-
getSearchAttribute
public <T> Attribute<T> getSearchAttribute(java.lang.String attributeName) throws CacheException
Retrieve the given named search attribute- Specified by:
getSearchAttributein interfaceEhcache- Type Parameters:
T- type of the attribute- Parameters:
attributeName- the name of the attribute to retrieve- Returns:
- the search attribute
- Throws:
CacheException- if no such attribute is defined for the given name
-
createQuery
public Query createQuery()
Create a new query builder for this cache- Specified by:
createQueryin interfaceEhcache- Returns:
- a new query builder
-
isSearchable
public boolean isSearchable()
Is this cache searchable?- Specified by:
isSearchablein interfaceEhcache- Returns:
- true if this cache is searchable
-
getLockForKey
protected Sync getLockForKey(java.lang.Object key)
Gets the lock for a given key- Parameters:
key- the key we want the lock for- Returns:
- the lock object for the passed in key
-
acquireReadLockOnKey
public void acquireReadLockOnKey(java.lang.Object key)
Acquires the proper read lock for a given cache key- Specified by:
acquireReadLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via locking
-
acquireWriteLockOnKey
public void acquireWriteLockOnKey(java.lang.Object key)
Acquires the proper write lock for a given cache key- Specified by:
acquireWriteLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via locking
-
tryReadLockOnKey
public boolean tryReadLockOnKey(java.lang.Object key, long timeout) throws java.lang.InterruptedExceptionTry to get a read lock on a given key. If can't get it in timeout millis then return a boolean telling that it didn't get the lock- Specified by:
tryReadLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via lockingtimeout- - millis until giveup on getting the lock- Returns:
- whether the lock was awarded
- Throws:
java.lang.InterruptedException- in case the thread was interrupted
-
tryWriteLockOnKey
public boolean tryWriteLockOnKey(java.lang.Object key, long timeout) throws java.lang.InterruptedExceptionTry to get a write lock on a given key. If can't get it in timeout millis then return a boolean telling that it didn't get the lock- Specified by:
tryWriteLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via lockingtimeout- - millis until giveup on getting the lock- Returns:
- whether the lock was awarded
- Throws:
java.lang.InterruptedException- in case the thread was interrupted
-
releaseReadLockOnKey
public void releaseReadLockOnKey(java.lang.Object key)
Release a held read lock for the passed in key- Specified by:
releaseReadLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via locking
-
releaseWriteLockOnKey
public void releaseWriteLockOnKey(java.lang.Object key)
Release a held write lock for the passed in key- Specified by:
releaseWriteLockOnKeyin interfaceEhcache- Parameters:
key- - The key that retrieves a value that you want to protect via locking
-
isReadLockedByCurrentThread
public boolean isReadLockedByCurrentThread(java.lang.Object key) throws java.lang.UnsupportedOperationExceptionReturns true if a read lock for the key is held by the current threadOnly Terracotta clustered cache instances currently support querying a thread's read lock hold status.
- Specified by:
isReadLockedByCurrentThreadin interfaceEhcache- Parameters:
key- the key- Returns:
- true if a read lock for the key is held by the current thread
- Throws:
java.lang.UnsupportedOperationException- if querying the read lock state is not supported
-
isWriteLockedByCurrentThread
public boolean isWriteLockedByCurrentThread(java.lang.Object key)
Returns true if a write lock for the key is held by the current thread- Specified by:
isWriteLockedByCurrentThreadin interfaceEhcache- Parameters:
key- the key- Returns:
- true if a write lock for the key is held by the current thread
-
isClusterBulkLoadEnabled
public boolean isClusterBulkLoadEnabled() throws java.lang.UnsupportedOperationException, TerracottaNotRunningExceptionReturns true if at least one node in the cluster is in bulk-load mode. Returns false otherwise.NOTE: if
Ehcache.isNodeBulkLoadEnabled()returns true, this method will always return true. Applies to caches clustered with Terracotta only.- Specified by:
isClusterBulkLoadEnabledin interfaceEhcache- Returns:
- true if the cache is in bulk-load mode cluster-wide, false otherwise
- Throws:
java.lang.UnsupportedOperationException- if the cache is not clustered with TerracottaTerracottaNotRunningException
-
isNodeBulkLoadEnabled
public boolean isNodeBulkLoadEnabled() throws java.lang.UnsupportedOperationException, TerracottaNotRunningExceptionReturns true if the current node is in bulk-load mode. Returns false otherwise.NOTE: if this method returns true,
Ehcache.isClusterBulkLoadEnabled()method will always return true. Applies to caches clustered with Terracotta only.- Specified by:
isNodeBulkLoadEnabledin interfaceEhcache- Returns:
- true if the cache is in coherent mode cluster-wide, false otherwise
- Throws:
java.lang.UnsupportedOperationException- if the cache is not clustered with TerracottaTerracottaNotRunningException
-
setNodeBulkLoadEnabled
public void setNodeBulkLoadEnabled(boolean enabledBulkLoad) throws java.lang.UnsupportedOperationException, TerracottaNotRunningExceptionEnable/disable bulk-load mode in this node for this cache. CallingsetBulkLoadEnabled(true)when the cache is already in bulk-load mode or callingsetBulkLoadEnabled(false)when already NOT in bulk-load mode will be a no-op.Applies to caches clustered with Terracotta only.
When using Terracotta clustered caches with nonstop enabled, the timeout used by this method is
NonstopConfiguration.getBulkOpsTimeoutMultiplyFactor()times the timeout value in the nonstop config.- Specified by:
setNodeBulkLoadEnabledin interfaceEhcache- Parameters:
enabledBulkLoad- true enables bulk-load, false disables it if not already disabled- Throws:
java.lang.UnsupportedOperationException- if the cache is not clustered with TerracottaTerracottaNotRunningException
-
waitUntilClusterBulkLoadComplete
public void waitUntilClusterBulkLoadComplete() throws java.lang.UnsupportedOperationException, TerracottaNotRunningExceptionThis method waits until all the connected nodes have disabled bulk-load. Or in other words, calling this method will block until all connected nodes in the cluster disables bulk-load. If none of the nodes did not enable bulk-load this method will return immediatelyApplies to caches clustered with Terracotta only.
- Specified by:
waitUntilClusterBulkLoadCompletein interfaceEhcache- Throws:
java.lang.UnsupportedOperationException- if the cache is not clustered with TerracottaTerracottaNotRunningException
-
recalculateSize
public void recalculateSize(java.lang.Object key)
Recalculate the size of the element mapped to the key- Specified by:
recalculateSizein interfaceInternalEhcache- Parameters:
key- the key
-
-