ehcache

net.sf.ehcache
Class Cache

java.lang.Object
  extended by net.sf.ehcache.Cache
All Implemented Interfaces:
java.lang.Cloneable, Ehcache

public class Cache
extends java.lang.Object
implements Ehcache

Cache is the central class in ehcache. Caches have Elements and are managed by the CacheManager. The Cache performs logical actions. It delegates physical implementations to its Stores.

A reference to a Cache can be obtained through the CacheManager. A Cache thus obtained is guaranteed to have status Status.STATUS_ALIVE. This status is checked for any method which throws IllegalStateException and the same thrown if it is not alive. This would normally happen if a call is made after CacheManager.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: Cache.java 704 2008-07-13 00:17:52Z gregluck $
Author:
Greg Luck

Nested Class Summary
(package private)  class Cache.KeyedFuture
          Used to store a future and the key it is in respect of
 
Field Summary
static java.lang.String DEFAULT_CACHE_NAME
          A reserved word for cache names.
static long DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS
          The default interval between runs of the expiry thread.
static java.lang.String NET_SF_EHCACHE_DISABLED
          System Property based method of disabling ehcache.
 
Constructor Summary
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 Constructor

The ConfigurationFactory and clients can create these.

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 Constructor

The ConfigurationFactory and clients can create these.

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 Constructor

The ConfigurationFactory and clients can create these.

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.2.4 Constructor

The ConfigurationFactory and clients can create these.

 
Method Summary
(package private)  edu.emory.mathcs.backport.java.util.concurrent.Future asynchronousLoad(java.lang.Object key, CacheLoader specificLoader, java.lang.Object argument)
          Does the asynchronous loading.
(package private)  edu.emory.mathcs.backport.java.util.concurrent.Future asynchronousLoadAll(java.util.Collection keys, java.lang.Object argument)
          Does the asynchronous loading.
 void bootstrap()
          Bootstrap command.
 long calculateInMemorySize()
          Gets the size of the memory store for this cache.
 void clearStatistics()
          Resets statistics counters back to 0.
 java.lang.Object clone()
          Clones a cache.
protected  Store createDiskStore()
          Creates a disk store when either: overflowToDisk is enabled diskPersistent is enabled
 void dispose()
          Starts an orderly shutdown of the Cache.
 boolean equals(java.lang.Object object)
          An equals method which follows the contract of Object.equals(Object)

An Cache is equal to another one if it implements Ehcache and has the same GUID.

 void evictExpiredElements()
          Causes all elements stored in the Cache to be synchronously checked for expiry, and if expired, evicted.
 void flush()
          Flushes all cache items from memory to the disk store, and from the DiskStore to disk.
 Element get(java.lang.Object key)
          Gets an element from the cache.
 Element get(java.io.Serializable key)
          Gets an element from the cache.
 java.util.Map getAllWithLoader(java.util.Collection keys, java.lang.Object loaderArgument)
          Warning: This method is related to the JSR107 specification, which is in draft.
 float getAverageGetTime()
          The average get time in ms.
 BootstrapCacheLoader getBootstrapCacheLoader()
          Accessor for the BootstrapCacheLoader associated with this cache.
 CacheConfiguration getCacheConfiguration()
          Gets the cache configuration this cache was created with.
 RegisteredEventListeners getCacheEventNotificationService()
          Use this to access the service in order to register and unregister listeners
 CacheExceptionHandler getCacheExceptionHandler()
          Gets the ExceptionHandler on this Cache, or null if there isn't one.
 CacheLoader getCacheLoader()
          Gets the CacheLoader registered in this cache
 CacheManager getCacheManager()
          Gets the CacheManager managing this cache.
 long getDiskExpiryThreadIntervalSeconds()
          Deprecated. Get this from the configuration
(package private)  Store getDiskStore()
          Gets the internal DiskStore.
 int getDiskStoreHitCount()
          Deprecated. Use Statistics
 int getDiskStoreSize()
          Returns the number of elements in the disk store.
(package private)  edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor getExecutorService()
           
 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.
 int getHitCount()
          Deprecated. Use Statistics
 java.util.List getKeys()
          Returns a list of all element keys in the cache, whether or not they are expired.
 java.util.List getKeysNoDuplicateCheck()
          Returns a list of all elements in the cache, whether or not they are expired.
 java.util.List getKeysWithExpiryCheck()
          Returns a list of all element keys in the cache.
 int getMaxElementsInMemory()
          Deprecated. Get this from the configuration
 int getMaxElementsOnDisk()
          Deprecated. Get this from the configuration
(package private)  MemoryStore getMemoryStore()
          Gets the internal MemoryStore.
 MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy()
          Deprecated. Get this from the configuration
 int getMemoryStoreHitCount()
          Deprecated. Use Statistics
 long getMemoryStoreSize()
          Returns the number of elements in the memory store.
 int getMissCountExpired()
          Deprecated. Use Statistics
 int getMissCountNotFound()
          Deprecated. Use Statistics
 java.lang.String getName()
          Gets the cache name.
 Element getQuiet(java.lang.Object key)
          Gets an element from the cache, without updating Element statistics.
 Element getQuiet(java.io.Serializable key)
          Gets an element from the cache, without updating Element statistics.
 int getSize()
          Gets the size of the cache.
 Statistics getStatistics()
          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 Statistics.STATISTICS_ACCURACY_BEST_EFFORT.

 int getStatisticsAccuracy()
          Accurately measuring statistics can be expensive.
 Status getStatus()
          Gets the status attribute of the Cache.
 long getTimeToIdleSeconds()
          Deprecated. Get this from the configuration
 long getTimeToLiveSeconds()
          Deprecated. Get this from the configuration
 Element getWithLoader(java.lang.Object key, CacheLoader loader, java.lang.Object loaderArgument)
          Warning: This method is related to the JSR107 specification, which is in draft.
 int hashCode()
          Returns a hash code value for the object.
 void initialise()
          Newly created caches do not have a MemoryStore or a DiskStore.
 boolean isDisabled()
          Whether this cache is disabled.
 boolean isDiskPersistent()
          Deprecated. Get this from the configuration *
protected  boolean isDiskStore()
          Whether this cache uses a disk store
 boolean isElementInMemory(java.lang.Object key)
          Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.
 boolean isElementInMemory(java.io.Serializable key)
          Whether an Element is stored in the cache in Memory, indicating a very low cost of retrieval.
 boolean isElementOnDisk(java.lang.Object key)
          Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.
 boolean isElementOnDisk(java.io.Serializable key)
          Whether an Element is stored in the cache on Disk, indicating a higher cost of retrieval.
 boolean isEternal()
          Deprecated. Get this from the configuration
 boolean isExpired(Element element)
          Checks whether this cache element has expired.
 boolean isKeyInCache(java.lang.Object key)
          An inexpensive check to see if the key exists in the cache.
 boolean isOverflowToDisk()
          Deprecated. Get this from the configuration
 boolean isValueInCache(java.lang.Object value)
          An extremely expensive check to see if the value exists in the cache.
 void load(java.lang.Object key)
          Warning: This method is related to the JSR107 specification, which is in draft.
 void loadAll(java.util.Collection keys, java.lang.Object argument)
          Warning: This method is related to the JSR107 specification, which is in draft.
 void put(Element element)
          Put an element in the cache.
 void put(Element element, boolean doNotNotifyCacheReplicators)
          Put an element in the cache.
 void putQuiet(Element element)
          Put an element in the cache, without updating statistics, or updating listeners.
 void registerCacheExtension(CacheExtension cacheExtension)
          Register a CacheExtension with the cache.
 boolean remove(java.lang.Object key)
          Removes an Element from the Cache.
 boolean remove(java.lang.Object key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
 boolean remove(java.io.Serializable key)
          Removes an Element from the Cache.
 boolean remove(java.io.Serializable key, boolean doNotNotifyCacheReplicators)
          Removes an Element from the Cache.
 void removeAll()
          Removes all cached items.
 void removeAll(boolean doNotNotifyCacheReplicators)
          Removes all cached items.
 boolean removeQuiet(java.lang.Object key)
          Removes an Element from the Cache, without notifying listeners.
 boolean removeQuiet(java.io.Serializable key)
          Removes an Element from the Cache, without notifying listeners.
 void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader)
          Sets the bootstrap cache loader.
 void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler)
          Sets an ExceptionHandler on the Cache.
 void setCacheLoader(CacheLoader cacheLoader)
          Setter for the CacheLoader.
 void setCacheManager(CacheManager cacheManager)
          For use by CacheManager.
 void setDisabled(boolean disabled)
          Disables or enables this cache.
 void setDiskStorePath(java.lang.String diskStorePath)
          DiskStore paths can conflict between CacheManager instances.
 void setName(java.lang.String name)
          Sets the cache name which will name.
 void setStatisticsAccuracy(int statisticsAccuracy)
          Sets the statistics accuracy.
 java.lang.String toString()
          Returns a String representation of Cache.
 void unregisterCacheExtension(CacheExtension cacheExtension)
          Unregister a CacheExtension with the cache.
 
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
 

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=true in 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.

See Also:
Constant Field Values
Constructor Detail

Cache

public Cache(java.lang.String name,
             int maxElementsInMemory,
             boolean overflowToDisk,
             boolean eternal,
             long timeToLiveSeconds,
             long timeToIdleSeconds)
1.0 Constructor.

The ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
overflowToDisk - whether to use the disk store
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
Since:
1.0

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 ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
overflowToDisk - whether to use the disk store
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
diskPersistent - whether to persist the cache to disk between JVM restarts
diskExpiryThreadIntervalSeconds - how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended
Since:
1.1

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 Constructor

The ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
memoryStoreEvictionPolicy - one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.
overflowToDisk - whether to use the disk store
diskStorePath - this parameter is ignored. CacheManager sets it using setter injection.
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
diskPersistent - whether to persist the cache to disk between JVM restarts
diskExpiryThreadIntervalSeconds - how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended
registeredEventListeners - a notification service. Optionally null, in which case a new one with no registered listeners will be created.
Since:
1.2

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 Constructor

The ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
memoryStoreEvictionPolicy - one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.
overflowToDisk - whether to use the disk store
diskStorePath - this parameter is ignored. CacheManager sets it using setter injection.
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
diskPersistent - whether to persist the cache to disk between JVM restarts
diskExpiryThreadIntervalSeconds - how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended
registeredEventListeners - 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

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 Constructor

The ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
memoryStoreEvictionPolicy - one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.
overflowToDisk - whether to use the disk store
diskStorePath - this parameter is ignored. CacheManager sets it using setter injection.
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
diskPersistent - whether to persist the cache to disk between JVM restarts
diskExpiryThreadIntervalSeconds - how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended
registeredEventListeners - 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.4

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.2.4 Constructor

The ConfigurationFactory and clients can create these.

A client can specify their own settings here and pass the Cache object into CacheManager.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
memoryStoreEvictionPolicy - one of LRU, LFU and FIFO. Optionally null, in which case it will be set to LRU.
overflowToDisk - whether to use the disk store
diskStorePath - this parameter is ignored. CacheManager sets it using setter injection.
eternal - whether the elements in the cache are eternal, i.e. never expire
timeToLiveSeconds - the default amount of time to live for an element from its creation date
timeToIdleSeconds - the default amount of time to live for an element from its last accessed or modified date
diskPersistent - whether to persist the cache to disk between JVM restarts
diskExpiryThreadIntervalSeconds - how often to run the disk store expiry thread. A large number of 120 seconds plus is recommended
registeredEventListeners - 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.
diskSpoolBufferSizeMB - the amount of memory to allocate the write buffer for puts to the DiskStore.
Since:
1.2.4
Method Detail

initialise

public void initialise()
Newly created caches do not have a MemoryStore or a DiskStore.

This method creates those and makes the cache ready to accept elements

Specified by:
initialise in interface Ehcache

createDiskStore

protected Store createDiskStore()
Creates a disk store when either:
  1. overflowToDisk is enabled
  2. diskPersistent is enabled


isDiskStore

protected boolean isDiskStore()
Whether this cache uses a disk store

Returns:
true if the cache either overflows to disk or is disk persistent

bootstrap

public void bootstrap()
Bootstrap command. This must be called after the Cache is intialised, during CacheManager initialisation. If loads are synchronous, they will complete before the CacheManager initialise completes, otherwise they will happen in the background.

Specified by:
bootstrap in interface Ehcache

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:

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 cirucmstances.

Specified by:
put in interface Ehcache
Parameters:
element - An object. If Serializable it can fully participate in replication and the DiskStore.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
java.lang.IllegalArgumentException - if the element is null
CacheException

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:

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 cirucmstances.

Specified by:
put in interface Ehcache
Parameters:
element - An object. If Serializable it can fully participate in replication and the DiskStore.
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 not Status.STATUS_ALIVE
java.lang.IllegalArgumentException - if the element is null
CacheException

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 with getQuiet(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 cirucmstances.

Specified by:
putQuiet in interface Ehcache
Parameters:
element - An object. If Serializable it can fully participate in replication and the DiskStore.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
java.lang.IllegalArgumentException - if the element is null
CacheException

get

public final Element get(java.io.Serializable key)
                  throws java.lang.IllegalStateException,
                         CacheException
Gets an element from the cache. Updates Element Statistics

Note 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 get

Synchronization is handled within the method.

Specified by:
get in interface Ehcache
Parameters:
key - a serializable value
Returns:
the element, or null, if it does not exist.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException
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 Statistics

Note 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 get

Synchronization is handled within the method.

Specified by:
get in interface Ehcache
Parameters:
key - an Object value
Returns:
the element, or null, if it does not exist.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException
Since:
1.2
See Also:
isExpired(net.sf.ehcache.Element)

getWithLoader

public Element getWithLoader(java.lang.Object key,
                             CacheLoader loader,
                             java.lang.Object loaderArgument)
                      throws CacheException
Warning: This method is related to the JSR107 specification, which is in draft. It is subject to change without notice.

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.

If the loader decides to assign a null value to the Element, an Element with a null value is created and stored in the cache.

Because this method may take a long time to complete, it is not synchronized. The underlying cache operations are synchronized.

Specified by:
getWithLoader in interface Ehcache
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 used
loaderArgument - an argument to pass to the CacheLoader.
Returns:
an element if it existed or could be loaded, otherwise null
Throws:
CacheException

load

public void load(java.lang.Object key)
          throws CacheException
Warning: This method is related to the JSR107 specification, which is in draft. It is subject to change without notice.

The 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:
load in interface Ehcache
Parameters:
key - key whose associated value to be loaded using the associated cacheloader if this cache doesn't contain it.
Throws:
CacheException

getAllWithLoader

public java.util.Map getAllWithLoader(java.util.Collection keys,
                                      java.lang.Object loaderArgument)
                               throws CacheException
Warning: This method is related to the JSR107 specification, which is in draft. It is subject to change without notice.

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 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:
getAllWithLoader in interface Ehcache
Parameters:
keys - a collection of keys to be returned/loaded
loaderArgument - 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

loadAll

public void loadAll(java.util.Collection keys,
                    java.lang.Object argument)
             throws CacheException
Warning: This method is related to the JSR107 specification, which is in draft. It is subject to change without notice.

The 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. 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:
loadAll in interface Ehcache
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.

Synchronization is handled within the method.

Specified by:
getQuiet in interface Ehcache
Parameters:
key - a serializable value
Returns:
the element, or null, if it does not exist.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException
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.

Synchronization is handled within the method.

Specified by:
getQuiet in interface Ehcache
Parameters:
key - a serializable value
Returns:
the element, or null, if it does not exist.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException
Since:
1.2
See Also:
isExpired(net.sf.ehcache.Element)

getKeys

public final java.util.List getKeys()
                             throws java.lang.IllegalStateException,
                                    CacheException
Returns a list of all element keys in the cache, whether or not they are expired.

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). On a single cpu 1.8Ghz P4, approximately 8ms is required for each 1000 entries.

Specified by:
getKeys in interface Ehcache
Returns:
a list of Object keys
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

getKeysWithExpiryCheck

public final java.util.List getKeysWithExpiryCheck()
                                            throws java.lang.IllegalStateException,
                                                   CacheException
Returns 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 syncrhonized, 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:
getKeysWithExpiryCheck in interface Ehcache
Returns:
a list of Object keys
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

getKeysNoDuplicateCheck

public final java.util.List getKeysNoDuplicateCheck()
                                             throws java.lang.IllegalStateException
Returns 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:
getKeysNoDuplicateCheck in interface Ehcache
Returns:
a list of Object keys
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

remove

public final boolean remove(java.io.Serializable key)
                     throws java.lang.IllegalStateException
Removes an Element from 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 cirucmstances.

Specified by:
remove in interface Ehcache
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 not Status.STATUS_ALIVE

remove

public final boolean remove(java.lang.Object key)
                     throws java.lang.IllegalStateException
Removes an Element from 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 cirucmstances.

Specified by:
remove in interface Ehcache
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 not Status.STATUS_ALIVE
Since:
1.2

remove

public final boolean remove(java.io.Serializable key,
                            boolean doNotNotifyCacheReplicators)
                     throws java.lang.IllegalStateException
Removes an Element from 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 cirucmstances.

Specified by:
remove in interface Ehcache
Parameters:
key - the element key to operate on
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
Returns:
true if the element was removed, false if it was not found in the cache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

remove

public final boolean remove(java.lang.Object key,
                            boolean doNotNotifyCacheReplicators)
                     throws java.lang.IllegalStateException
Removes an Element from 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:
remove in interface Ehcache
Parameters:
key - the element key to operate on
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
Returns:
true if the element was removed, false if it was not found in the cache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

removeQuiet

public final boolean removeQuiet(java.io.Serializable key)
                          throws java.lang.IllegalStateException
Removes an Element from the Cache, without notifying listeners. This also removes it from any stores it may be in.

Synchronization is handled within the method.

Specified by:
removeQuiet in interface Ehcache
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 not Status.STATUS_ALIVE

removeQuiet

public final boolean removeQuiet(java.lang.Object key)
                          throws java.lang.IllegalStateException
Removes an Element from the Cache, without notifying listeners. This also removes it from any stores it may be in.

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 cirucmstances.

Specified by:
removeQuiet in interface Ehcache
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 not Status.STATUS_ALIVE
Since:
1.2

removeAll

public void removeAll()
               throws java.lang.IllegalStateException,
                      CacheException
Removes 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 cirucmstances.

Specified by:
removeAll in interface Ehcache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

removeAll

public void removeAll(boolean doNotNotifyCacheReplicators)
               throws java.lang.IllegalStateException,
                      CacheException
Removes 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 cirucmstances.

Specified by:
removeAll in interface Ehcache
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 not Status.STATUS_ALIVE
CacheException

dispose

public void dispose()
             throws java.lang.IllegalStateException
Starts an orderly shutdown of the Cache. Steps are:
  1. Completes any outstanding CacheLoader loads.
  2. Disposes any cache extensions.
  3. Disposes any cache event listeners. The listeners normally complete, so for example distributed caching operations will complete.
  4. Flushes all cache items from memory to the disk store, if any
  5. changes status to shutdown, so that any cache operations after this point throw IllegalStateException
This method should be invoked only by CacheManager, as a cache's lifecycle is bound into that of it's cache manager.

Specified by:
dispose in interface Ehcache
Throws:
java.lang.IllegalStateException - if the cache is already Status.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:
getCacheConfiguration in interface Ehcache

flush

public final void flush()
                 throws java.lang.IllegalStateException,
                        CacheException
Flushes all cache items from memory to the disk store, and from the DiskStore to disk.

Specified by:
flush in interface Ehcache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

getSize

public final int getSize()
                  throws java.lang.IllegalStateException,
                         CacheException
Gets the size of the cache. This is a subtle concept. See below.

The size is the number of Elements in the MemoryStore plus the number of Elements in the DiskStore.

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.

Specified by:
getSize in interface Ehcache
Returns:
The size value
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

calculateInMemorySize

public final long calculateInMemorySize()
                                 throws java.lang.IllegalStateException,
                                        CacheException
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:
calculateInMemorySize in interface Ehcache
Returns:
the approximate size of the memory store in bytes
Throws:
java.lang.IllegalStateException
CacheException

getMemoryStoreSize

public final long getMemoryStoreSize()
                              throws java.lang.IllegalStateException
Returns the number of elements in the memory store.

Specified by:
getMemoryStoreSize in interface Ehcache
Returns:
the number of elements in the memory store
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

getDiskStoreSize

public final int getDiskStoreSize()
                           throws java.lang.IllegalStateException
Returns the number of elements in the disk store.

Specified by:
getDiskStoreSize in interface Ehcache
Returns:
the number of elements in the disk store.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

getStatus

public final Status getStatus()
Gets the status attribute of the Cache.

Specified by:
getStatus in interface Ehcache
Returns:
The status value from the Status enum class

getHitCount

public final int getHitCount()
Deprecated. Use Statistics

The number of times a requested item was found in the cache.

The internal representation of this statistic has been changed to a long to cater for real world situations when an int is not sufficient to hold it. If the statistic is larger than Integer.MAX_VALUE a nonsensical value will be returned. Use Statistics which contains this statistic.

Returns:
the number of times a requested item was found in the cache

getMemoryStoreHitCount

public final int getMemoryStoreHitCount()
Deprecated. Use Statistics

Number of times a requested item was found in the Memory Store.

The internal representation of this statistic has been changed to a long to cater for real world situations when an int is not sufficient to hold it. If the statistic is larger than Integer.MAX_VALUE a nonsensical value will be returned. Use Statistics which contains this statistic.

Returns:
Number of times a requested item was found in the Memory Store.

getDiskStoreHitCount

public final int getDiskStoreHitCount()
Deprecated. Use Statistics

Number of times a requested item was found in the Disk Store.

The internal representation of this statistic has been changed to a long to cater for real world situations when an int is not sufficient to hold it. If the statistic is larger than Integer.MAX_VALUE a nonsensical value will be returned. Use Statistics which contains this statistic.


getMissCountNotFound

public final int getMissCountNotFound()
Deprecated. Use Statistics

Number of times a requested element was not found in the cache. This may be because it expired, in which case this will also be recorded in getMissCountExpired(), or because it was simply not there.

The internal representation of this statistic has been changed to a long to cater for real world situations when an int is not sufficient to hold it. If the statistic is larger than Integer.MAX_VALUE a nonsensical value will be returned. Use Statistics which contains this statistic.


getMissCountExpired

public final int getMissCountExpired()
Deprecated. Use Statistics

Number of times a requested element was found but was expired.

The internal representation of this statistic has been changed to a long to cater for real world situations when an int is not sufficient to hold it. If the statistic is larger than Integer.MAX_VALUE a nonsensical value will be returned. Use Statistics which contains this statistic.


getName

public final java.lang.String getName()
Gets the cache name.

Specified by:
getName in interface Ehcache

setName

public final void setName(java.lang.String name)
                   throws java.lang.IllegalArgumentException
Sets the cache name which will name.

Specified by:
setName in interface Ehcache
Parameters:
name - the name of the cache. Should not be null. Should also not contain any '/' characters, as these interfere with distribution
Throws:
java.lang.IllegalArgumentException - if an illegal name is used.

getTimeToIdleSeconds

public final long getTimeToIdleSeconds()
Deprecated. Get this from the configuration

Gets timeToIdleSeconds.

Specified by:
getTimeToIdleSeconds in interface Ehcache

getTimeToLiveSeconds

public final long getTimeToLiveSeconds()
Deprecated. Get this from the configuration

Gets timeToLiveSeconds.

Specified by:
getTimeToLiveSeconds in interface Ehcache

isEternal

public final boolean isEternal()
Deprecated. Get this from the configuration

Are elements eternal.

Specified by:
isEternal in interface Ehcache

isOverflowToDisk

public final boolean isOverflowToDisk()
Deprecated. Get this from the configuration

Does the overflow go to disk.

Specified by:
isOverflowToDisk in interface Ehcache

getMaxElementsInMemory

public final int getMaxElementsInMemory()
Deprecated. Get this from the configuration

Gets the maximum number of elements to hold in memory.

Specified by:
getMaxElementsInMemory in interface Ehcache

getMaxElementsOnDisk

public int getMaxElementsOnDisk()
Deprecated. Get this from the configuration

Gets the maximum number of elements to hold on Disk

Specified by:
getMaxElementsOnDisk in interface Ehcache

getMemoryStoreEvictionPolicy

public final MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy()
Deprecated. Get this from the configuration

The policy used to evict elements from the MemoryStore. This can be one of:
  1. LRU - least recently used
  2. LFU - least frequently used
  3. FIFO - first in first out, the oldest element by creation time
The default value is LRU

Specified by:
getMemoryStoreEvictionPolicy in interface Ehcache
Since:
1.2

isDiskPersistent

public final boolean isDiskPersistent()
Deprecated. Get this from the configuration *

Specified by:
isDiskPersistent in interface Ehcache
Returns:
true if the cache overflows to disk and the disk is persistent between restarts

getDiskExpiryThreadIntervalSeconds

public final long getDiskExpiryThreadIntervalSeconds()
Deprecated. Get this from the configuration

Specified by:
getDiskExpiryThreadIntervalSeconds in interface Ehcache
Returns:
the interval between runs of the expiry thread, where it checks the disk store for expired elements. It is not the the timeToLiveSeconds.

toString

public final java.lang.String toString()
Returns a String representation of Cache.

Specified by:
toString in interface Ehcache
Overrides:
toString in class java.lang.Object

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:

  1. the idle time is non-zero and has elapsed, unless the cache is eternal; or
  2. the time to live is non-zero and has elapsed, unless the cache is eternal; or
  3. the value of the element is null.

Specified by:
isExpired in interface Ehcache
Parameters:
element - the element to check
Returns:
true if it has expired
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
java.lang.NullPointerException - if the element is null

clone

public final java.lang.Object 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 LruMemoryStore or DiskStore has been created.

A new, empty, RegisteredEventListeners is created on clone.

Specified by:
clone in interface Ehcache
Overrides:
clone in class java.lang.Object
Returns:
an object of type Cache
Throws:
java.lang.CloneNotSupportedException

getDiskStore

final Store getDiskStore()
                  throws java.lang.IllegalStateException
Gets the internal DiskStore.

Returns:
the DiskStore referenced by this cache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

getMemoryStore

final MemoryStore getMemoryStore()
                          throws java.lang.IllegalStateException
Gets the internal MemoryStore.

Returns:
the MemoryStore referenced by this cache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

getCacheEventNotificationService

public final RegisteredEventListeners getCacheEventNotificationService()
Use this to access the service in order to register and unregister listeners

Specified by:
getCacheEventNotificationService in interface Ehcache
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.

Specified by:
isElementInMemory in interface Ehcache
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.

Specified by:
isElementInMemory in interface Ehcache
Returns:
true if an element matching the key is found in memory
Since:
1.2

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.

Specified by:
isElementOnDisk in interface Ehcache
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.

Specified by:
isElementOnDisk in interface Ehcache
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.

Specified by:
getGuid in interface Ehcache
Returns:
the globally unique identifier for this cache instance. This is guaranteed to be unique.
Since:
1.2

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:
getCacheManager in interface Ehcache
Returns:
the manager or null if there is none

clearStatistics

public void clearStatistics()
                     throws java.lang.IllegalStateException
Resets statistics counters back to 0.

Specified by:
clearStatistics in interface Ehcache
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

getStatisticsAccuracy

public int getStatisticsAccuracy()
Accurately measuring statistics can be expensive. Returns the current accuracy setting.

Specified by:
getStatisticsAccuracy in interface Ehcache
Returns:
one of Statistics.STATISTICS_ACCURACY_BEST_EFFORT, Statistics.STATISTICS_ACCURACY_GUARANTEED, Statistics.STATISTICS_ACCURACY_NONE

setStatisticsAccuracy

public void setStatisticsAccuracy(int statisticsAccuracy)
Sets the statistics accuracy.

Specified by:
setStatisticsAccuracy in interface Ehcache
Parameters:
statisticsAccuracy - one of Statistics.STATISTICS_ACCURACY_BEST_EFFORT, Statistics.STATISTICS_ACCURACY_GUARANTEED, Statistics.STATISTICS_ACCURACY_NONE

evictExpiredElements

public void evictExpiredElements()
Causes all elements stored in the Cache to be synchronously checked for expiry, and if expired, evicted.

Specified by:
evictExpiredElements in interface Ehcache

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 aned be removed before the check gets to it, or vice versa.

Specified by:
isKeyInCache in interface Ehcache
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 aned 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:
isValueInCache in interface Ehcache
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 Statistics getStatistics()
                         throws java.lang.IllegalStateException
Gets an immutable Statistics object representing the Cache statistics at the time. How the statistics are calculated depends on the statistics accuracy setting. The only aspect of statistics sensitive to the accuracy setting is object size. How that is calculated is discussed below.

Best Effort Size

This result is returned when the statistics accuracy setting is Statistics.STATISTICS_ACCURACY_BEST_EFFORT.

The size is the number of Elements in the MemoryStore plus the number of Elements in the DiskStore.

This number is the actual number of elements, including expired elements that have not been removed. Any duplicates between stores are accounted for.

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.

Guaranteed Accuracy Size

This result is returned when the statistics accuracy setting is Statistics.STATISTICS_ACCURACY_GUARANTEED.

This method accounts for elements which might be expired or duplicated between stores. It take approximately 200ms per 1000 elements to execute.

Fast but non-accurate Size

This result is returned when the statistics accuracy setting is Statistics.STATISTICS_ACCURACY_NONE.

The number given may contain expired elements. In addition if the DiskStore is used it may contain some double counting of elements. It takes 6ms for 1000 elements to execute. Time to execute is O(log n). 50,000 elements take 36ms.

Note, the getSize() method will have the same value as the size reported by Statistics for the statistics accuracy of Statistics.STATISTICS_ACCURACY_BEST_EFFORT.

Specified by:
getStatistics in interface Ehcache
Returns:
the number of elements in the ehcache, with a varying degree of accuracy, depending on accuracy setting.
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

setCacheManager

public void setCacheManager(CacheManager cacheManager)
For use by CacheManager.

Specified by:
setCacheManager in interface Ehcache
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:
getBootstrapCacheLoader in interface Ehcache
Returns:
the BootstrapCacheLoader to use

setBootstrapCacheLoader

public void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader)
                             throws CacheException
Sets the bootstrap cache loader.

Specified by:
setBootstrapCacheLoader in interface Ehcache
Parameters:
bootstrapCacheLoader - the loader to be used
Throws:
CacheException - if this method is called after the cache is initialized

setDiskStorePath

public void setDiskStorePath(java.lang.String diskStorePath)
                      throws CacheException
DiskStore paths can conflict between CacheManager instances. This method allows the path to be changed.

Specified by:
setDiskStorePath in interface Ehcache
Parameters:
diskStorePath - the new path 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 of Object.equals(Object)

An Cache is equal to another one if it implements Ehcache and has the same GUID.

Overrides:
equals in class java.lang.Object
Parameters:
object - the reference object with which to compare.
Returns:
true if this object is the same as the obj argument; false otherwise.
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 by java.util.Hashtable.

The general contract of hashCode is:

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 JavaTM programming language.)

This implementation use the GUID of the cache.

Overrides:
hashCode in class java.lang.Object
Returns:
a hash code value for this object.
See Also:
Object.equals(Object), Hashtable

registerCacheExtension

public void registerCacheExtension(CacheExtension cacheExtension)
Register a CacheExtension with the cache. It will then be tied into the cache lifecycle.

If the CacheExtension is not initialised, initialise it.

Specified by:
registerCacheExtension in interface Ehcache

unregisterCacheExtension

public void unregisterCacheExtension(CacheExtension cacheExtension)
Unregister a CacheExtension with the cache. It will then be detached from the cache lifecycle.

Specified by:
unregisterCacheExtension in interface Ehcache

getAverageGetTime

public float getAverageGetTime()
The average get time in ms.

Specified by:
getAverageGetTime in interface Ehcache

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:
setCacheExceptionHandler in interface Ehcache
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:
getCacheExceptionHandler in interface Ehcache
See Also:
ExceptionHandlingDynamicCacheProxy

setCacheLoader

public void setCacheLoader(CacheLoader cacheLoader)
Setter for the CacheLoader. Changing the CacheLoader takes immediate effect.

Specified by:
setCacheLoader in interface Ehcache
Parameters:
cacheLoader - the loader to dynamically load new cache entries

getCacheLoader

public CacheLoader getCacheLoader()
Gets the CacheLoader registered in this cache

Specified by:
getCacheLoader in interface Ehcache
Returns:
the loader, or null if there is none

asynchronousLoad

edu.emory.mathcs.backport.java.util.concurrent.Future asynchronousLoad(java.lang.Object key,
                                                                       CacheLoader specificLoader,
                                                                       java.lang.Object argument)
Does the asynchronous loading.

Parameters:
specificLoader - a specific loader to use. If null the default loader is used.
Returns:
a Future which can be used to monitor execution

asynchronousLoadAll

edu.emory.mathcs.backport.java.util.concurrent.Future asynchronousLoadAll(java.util.Collection keys,
                                                                          java.lang.Object argument)
Does the asynchronous loading.

Parameters:
argument - the loader argument
Returns:
a Future which can be used to monitor execution

getExecutorService

edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor getExecutorService()
Returns:
Gets the executor service. This is not publically accessible.

isDisabled

public boolean isDisabled()
Whether this cache is disabled. "Disabled" means:
  1. bootstrap is disabled
  2. puts are discarded
  3. putQuites are discarded
In all other respects the cache continues as it is.

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.disabled system property is set.

Specified by:
isDisabled in interface Ehcache
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 the net.sf.ehcache.disabled system property is set

Specified by:
setDisabled in interface Ehcache
Parameters:
disabled - true if you wish to disable, false to enable
See Also:
isDisabled()

ehcache