ehcache

net.sf.ehcache.constructs.blocking
Class BlockingCache

java.lang.Object
  extended by net.sf.ehcache.constructs.blocking.BlockingCache
All Implemented Interfaces:
java.lang.Cloneable, Ehcache
Direct Known Subclasses:
SelfPopulatingCache

public class BlockingCache
extends java.lang.Object
implements Ehcache

A blocking decorator for an Ehcache, backed by a Ehcache.

It allows concurrent read access to elements already in the cache. If the element is null, other reads will block until an element with the same key is put into the cache.

This is useful for constructing read-through or self-populating caches.

This implementation uses the ReadWriteLockSync class. If you wish to use this class, you will need the concurrent package in your class path.

It features:

"Hashtable / synchronizedMap uses the "one big fat lock" approach to guard the mutable state of the map. That works, but is a big concurrency bottleneck, as you've observed. You went to the opposite extreme, one lock per key. That works (as long as you've got sufficient synchronization in the cache itself to protect its own data structures.)

Lock striping is a middle ground, partitioning keys into a fixed number of subsets, like the trick used at large theaters for will-call ticket pickup -- there are separate lines for "A-F, G-M, N-R, and S-Z". This way, there are a fixed number of locks, each guarding (hopefully) 1/Nth of the keys." - Brian Goetz

Further improvements to hashing suggested by Joe Bowbeer.

Version:
$Id: BlockingCache.java 1879 2010-02-13 13:18:03Z gbevin $
Author:
Greg Luck

Field Summary
protected  Ehcache cache
          The backing Cache
protected  int timeoutMillis
          The amount of time to block a thread before a LockTimeoutException is thrown
 
Constructor Summary
BlockingCache(Ehcache cache)
          Creates a BlockingCache which decorates the supplied cache.
BlockingCache(Ehcache cache, int numberOfStripes)
          Creates a BlockingCache which decorates the supplied cache.
 
Method Summary
 void bootstrap()
          Bootstrap command.
 long calculateInMemorySize()
          Gets the size of the memory store for this cache

Warning: This method can be very expensive to run.

 void clearStatistics()
          Resets statistics counters back to 0.
 java.lang.Object clone()
          Clones a cache.
 void disableDynamicFeatures()
          Disables dynamic configuration and disable/enable for this cache.
 void dispose()
          Flushes all cache items from memory to auxilliary caches and close the auxilliary caches.
 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)
          Looks up an entry.
 Element get(java.io.Serializable key)
          Gets an element from the cache.
 java.util.Map getAllWithLoader(java.util.Collection keys, java.lang.Object loaderArgument)
          This method is not appropriate to use with BlockingCache.
 float getAverageGetTime()
          The average get time in ms.
 BootstrapCacheLoader getBootstrapCacheLoader()
          Accessor for the BootstrapCacheLoader associated with this cache.
protected  Ehcache getCache()
          Retrieve the EHCache backing 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()
          Sets an ExceptionHandler on the Cache.
 CacheManager getCacheManager()
          Gets the CacheManager managing this cache.
 int getDiskStoreSize()
          Returns the number of elements in the disk store.
 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.
 java.lang.Object getInternalContext()
          This should not be used return some internal context (generally will be null)
 java.util.List getKeys()
          Returns the keys for this cache.
 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 elements in the cache.
 LiveCacheStatistics getLiveCacheStatistics()
          This is different from Ehcache.getStatistics() in the way that values returned from LiveCacheStatistics will reflect the current state of the cache (and not a snapshot of the cache when the api's were called like Ehcache.getStatistics())
protected  Sync getLockForKey(java.lang.Object key)
          Gets the Sync to use for a given key.
 long getMemoryStoreSize()
          Returns the number of elements in the memory store.
 java.lang.String getName()
          Returns this cache's 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.
 java.util.List<CacheExtension> getRegisteredCacheExtensions()
           
 java.util.List<CacheLoader> getRegisteredCacheLoaders()
           
 CacheWriter getRegisteredCacheWriter()
          Retrieves the CacheWriter that was registered for this cache.
 SampledCacheStatistics getSampledCacheStatistics()
          Returns sampled statistics for this cache.
 int getSize()
          Gets the size of the cache.
 int getSizeBasedOnAccuracy(int statisticsAccuracy)
          Accurately measuring statistics can be expensive.
 Statistics getStatistics()
          Gets an immutable Statistics object representing the Cache statistics at the time.
 int getStatisticsAccuracy()
          Accurately measuring statistics can be expensive.
 Status getStatus()
          Gets the status attribute of the Cache.
 int getTimeoutMillis()
          Gets the time to wait to acquire a lock.
 Element getWithLoader(java.lang.Object key, CacheLoader loader, java.lang.Object loaderArgument)
          This method is not appropriate to use with BlockingCache.
 CacheWriterManager getWriterManager()
          Obtain the writer manager that's used by this cache instance.
 void initialise()
          Newly created caches do not have a MemoryStore or a DiskStore.
 boolean isClusterCoherent()
          Returns true if the cache is in coherent mode cluster-wide.
 boolean isDisabled()
          Whether this cache is disabled.
 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 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 isNodeCoherent()
          Returns true if the cache is in coherent mode for the current node.
 boolean isSampledStatisticsEnabled()
          Returns if sampled statistics collection is enabled or disabled
 boolean isStatisticsEnabled()
          Returns true if statistics collection is enabled
 boolean isValueInCache(java.lang.Object value)
          An extremely expensive check to see if the value exists in the cache.
 java.lang.String liveness()
          Synchronized version of getName to test liveness of the object lock.
 void load(java.lang.Object key)
          This method is not appropriate to use with BlockingCache.
 void loadAll(java.util.Collection keys, java.lang.Object argument)
          This method is not appropriate to use with BlockingCache.
 void put(Element element)
          Adds an entry and unlocks it
 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 putWithWriter(Element element)
          Put an element in the cache writing through a CacheWriter.
 void registerCacheExtension(CacheExtension cacheExtension)
          Register a CacheExtension with the cache.
 void registerCacheLoader(CacheLoader cacheLoader)
          Register a CacheLoader with the cache.
 void registerCacheUsageListener(CacheUsageListener cacheUsageListener)
          Registers a CacheUsageListener which will be notified of the cache usage.
 void registerCacheWriter(CacheWriter cacheWriter)
          Register the CacheWriter for this 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.
 void removeCacheUsageListener(CacheUsageListener cacheUsageListener)
          Remove an already registered CacheUsageListener, if any.
 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.
 boolean removeWithWriter(java.lang.Object key)
          Removes an Element from the Cache and any stores it might be in.
 void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader)
          Sets the bootstrap cache loader.
 void setCacheExceptionHandler(CacheExceptionHandler cacheExceptionHandler)
          Sets an ExceptionHandler on the Cache.
 void setCacheManager(CacheManager cacheManager)
          Sets the 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 setNodeCoherent(boolean coherent)
          Sets the cache in coherent or incoherent mode depending on the parameter on this node.
 void setSampledStatisticsEnabled(boolean enabledStatistics)
          Enable/disable sampled statistics collection.
 void setStatisticsAccuracy(int statisticsAccuracy)
          Sets the statistics accuracy.
 void setStatisticsEnabled(boolean enabledStatistics)
          Enable/disable statistics collection.
 void setTimeoutMillis(int timeoutMillis)
          Sets the time to wait to acquire a lock.
 void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup)
          This class is used to access the transaction manager used during XA.
 void unregisterCacheExtension(CacheExtension cacheExtension)
          Unregister a CacheExtension with the cache.
 void unregisterCacheLoader(CacheLoader cacheLoader)
          Unregister a CacheLoader with the cache.
 void unregisterCacheWriter()
          Unregister the CacheWriter from the cache.
 void waitUntilClusterCoherent()
          This method waits until the cache is in coherent mode in all the connected nodes.
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface net.sf.ehcache.Ehcache
toString
 

Field Detail

cache

protected final Ehcache cache
The backing Cache


timeoutMillis

protected volatile int timeoutMillis
The amount of time to block a thread before a LockTimeoutException is thrown

Constructor Detail

BlockingCache

public BlockingCache(Ehcache cache,
                     int numberOfStripes)
              throws CacheException
Creates a BlockingCache which decorates the supplied cache.

Parameters:
cache - a backing ehcache.
numberOfStripes - how many stripes to has the keys against. Must be a non-zero even number. This is a trade-off between memory use and concurrency
Throws:
CacheException - shouldn't happen
Since:
1.2

BlockingCache

public BlockingCache(Ehcache cache)
              throws CacheException
Creates a BlockingCache which decorates the supplied cache.

Parameters:
cache - a backing ehcache.
Throws:
CacheException - shouldn't happen
Since:
1.6.1
Method Detail

getCache

protected Ehcache getCache()
Retrieve the EHCache backing cache

Returns:
the backing cache

getName

public java.lang.String getName()
Returns this cache's name

Specified by:
getName in interface Ehcache

setName

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

Specified by:
setName in interface Ehcache
Parameters:
name - the name of the cache. Should not be null.

isExpired

public 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 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 MemoryStore 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

getCacheEventNotificationService

public 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 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 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 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 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 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 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()
Resets statistics counters back to 0.

Specified by:
clearStatistics in interface Ehcache

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.

Specified by:
isKeyInCache in interface Ehcache
Parameters:
key - the key 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.

isValueInCache

public boolean isValueInCache(java.lang.Object value)
An extremely expensive check to see if the value exists in the cache.

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.

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

getLiveCacheStatistics

public LiveCacheStatistics getLiveCacheStatistics()
                                           throws java.lang.IllegalStateException
This is different from Ehcache.getStatistics() in the way that values returned from LiveCacheStatistics will reflect the current state of the cache (and not a snapshot of the cache when the api's were called like Ehcache.getStatistics())

Specified by:
getLiveCacheStatistics in interface Ehcache
Returns:
The LiveCacheStatistics associated with this cache
Throws:
java.lang.IllegalStateException

setCacheManager

public void setCacheManager(CacheManager cacheManager)
Sets the CacheManager

Specified by:
setCacheManager in interface Ehcache
Parameters:
cacheManager - the CacheManager this cache belongs to

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

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

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

dispose

public void dispose()
             throws java.lang.IllegalStateException
Flushes all cache items from memory to auxilliary caches and close the auxilliary caches.

Should be invoked only by CacheManager.

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

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

get

public Element get(java.lang.Object key)
            throws java.lang.RuntimeException,
                   LockTimeoutException
Looks up an entry. Blocks if the entry is null until a call to put(net.sf.ehcache.Element) is done to put an Element in.

If a put is not done, the lock is never released.

If this method throws an exception, it is the responsibility of the caller to catch that exception and call put(new Element(key, null)); to release the lock acquired. See SelfPopulatingCache for an example.

Note. If a LockTimeoutException is thrown while doing a get it means the lock was never acquired, therefore it is a threading error to call put(net.sf.ehcache.Element)

Specified by:
get in interface Ehcache
Parameters:
key - an Object value
Returns:
the element, or null, if it does not exist.
Throws:
LockTimeoutException - if timeout millis is non zero and this method has been unable to acquire a lock in that time
java.lang.RuntimeException - if thrown the lock will not released. Catch and callput(new Element(key, null)); to release the lock acquired.
See Also:
Ehcache.isExpired(net.sf.ehcache.Element)

getLockForKey

protected Sync getLockForKey(java.lang.Object key)
Gets the Sync to use for a given key.

Parameters:
key - the key
Returns:
one of a limited number of Sync's.

getWriterManager

public CacheWriterManager getWriterManager()
Obtain the writer manager that's used by this cache instance.

Specified by:
getWriterManager in interface Ehcache
Returns:
the writer manager that's set up for this cache

put

public void put(Element element)
Adds an entry and unlocks it

Specified by:
put in interface Ehcache
Parameters:
element - An object. If Serializable it can fully participate in replication and the DiskStore.

put

public 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:

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 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)

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

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 set for the cache, then this method has the same effect as cache.put().

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:

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

get

public 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

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)

getQuiet

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

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 Element getQuiet(java.lang.Object key)
                 throws java.lang.IllegalStateException,
                        CacheException
Gets an element from the cache, without updating Element statistics. Cache statistics are still updated.

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 java.util.List getKeys()
                       throws CacheException
Returns the keys for this cache.

Specified by:
getKeys in interface Ehcache
Returns:
a list of Object keys for this cache. This is not a live set, so it will not track changes to the key set.
Throws:
CacheException

getKeysWithExpiryCheck

public java.util.List getKeysWithExpiryCheck()
                                      throws java.lang.IllegalStateException,
                                             CacheException
Returns a list of all elements 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:
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 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 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, but only if an Element with the key actually existed.

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

remove

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

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

remove

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

Specified by:
remove in interface Ehcache
Parameters:
key - the key to remove
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 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.

Specified by:
remove in interface Ehcache
Parameters:
key - the key to remove
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 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.

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

removeQuiet

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

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

removeWithWriter

public boolean removeWithWriter(java.lang.Object key)
                         throws java.lang.IllegalStateException
Removes an Element from the Cache and any stores it might be in. This also removes through to a CacheWriter. If no CacheWriter has been set for the cache, then this method has the same effect as cache.remove().

Also notifies the CacheEventListener after the element was removed, but only if an El ement with the key actually existed.

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

removeAll

public void removeAll()
               throws java.lang.IllegalStateException,
                      CacheException
Removes all cached items.

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.

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

flush

public 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 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

getSizeBasedOnAccuracy

public int getSizeBasedOnAccuracy(int statisticsAccuracy)
                           throws java.lang.IllegalStateException,
                                  CacheException
Accurately measuring statistics can be expensive. Returns the size of the cache based on the accuracy setting

Specified by:
getSizeBasedOnAccuracy in interface Ehcache
Parameters:
statisticsAccuracy - one of Statistics.STATISTICS_ACCURACY_BEST_EFFORT, Statistics.STATISTICS_ACCURACY_GUARANTEED, Statistics.STATISTICS_ACCURACY_NONE
Returns:
the size of the cache based on the current accuracy setting
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
CacheException

calculateInMemorySize

public long calculateInMemorySize()
                           throws java.lang.IllegalStateException,
                                  CacheException
Gets the size of the memory store for this cache

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 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 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 Status getStatus()
Gets the status attribute of the Cache.

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

liveness

public java.lang.String liveness()
Synchronized version of getName to test liveness of the object lock.

The time taken for this method to return is a useful measure of runtime contention on the cache.

Returns:
the name of the cache.

setTimeoutMillis

public void setTimeoutMillis(int timeoutMillis)
Sets the time to wait to acquire a lock. This may be modified at any time.

The consequences of setting a timeout are:

  1. if a lock cannot be acquired in the given time a LockTimeoutException is thrown.
  2. if there is a queue of threads waiting for the first thread to complete, but it does not complete within the time out period, the successive threads may find that they have exceeded their lock timeouts and fail. This is usually a good thing because it stops a build up of threads from overwhelming a busy resource, but it does need to be considered in the design of user interfaces. The timeout should be set no greater than the time a user would be expected to wait before considering the action will never return
  3. it will be common to see a number of threads timeout trying to get the same lock. This is a normal and desired consequence.
The consequences of not setting a timeout (or setting it to 0) are:
  1. There are no partial failures in the system. But there is a greater possibility that a temporary overload in one part of the system can cause a back up that may take a long time to recover from.
  2. A failing method that perhaps fails because a resource is overloaded will be hit by each thread in turn, no matter whether there is a still a user who cares about getting a response.

Parameters:
timeoutMillis - the time in ms. Must be a positive number. 0 means wait forever.

getTimeoutMillis

public int getTimeoutMillis()
Gets the time to wait to acquire a lock.

Returns:
the time in ms.

registerCacheExtension

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

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

getRegisteredCacheExtensions

public java.util.List<CacheExtension> getRegisteredCacheExtensions()
Specified by:
getRegisteredCacheExtensions in interface Ehcache
Returns:
the cache extensions as a live list

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.

Specified by:
setCacheExceptionHandler in interface Ehcache

getCacheExceptionHandler

public CacheExceptionHandler getCacheExceptionHandler()
Sets an ExceptionHandler on the Cache. If one is already set, it is overwritten.

Specified by:
getCacheExceptionHandler in interface Ehcache

registerCacheLoader

public void registerCacheLoader(CacheLoader cacheLoader)
Register a CacheLoader with the cache. It will then be tied into the cache lifecycle.

If the CacheLoader is not initialised, initialise it.

Specified by:
registerCacheLoader in interface Ehcache
Parameters:
cacheLoader - A Cache Loader to register

unregisterCacheLoader

public void unregisterCacheLoader(CacheLoader cacheLoader)
Unregister a CacheLoader with the cache. It will then be detached from the cache lifecycle.

Specified by:
unregisterCacheLoader in interface Ehcache
Parameters:
cacheLoader - A Cache Loader to unregister

getRegisteredCacheLoaders

public java.util.List<CacheLoader> getRegisteredCacheLoaders()
Specified by:
getRegisteredCacheLoaders in interface Ehcache
Returns:
the cache loaders as a live list

registerCacheWriter

public void registerCacheWriter(CacheWriter cacheWriter)
Register the CacheWriter for this cache. It will then be tied into the cache lifecycle.

If the CacheWriter is not initialised, initialise it.

Specified by:
registerCacheWriter in interface Ehcache
Parameters:
cacheWriter - A CacheWriter to register

unregisterCacheWriter

public void unregisterCacheWriter()
Unregister the CacheWriter from the cache. It will then be detached from the cache lifecycle.

If not CacheWriter was registered beforehand this operation has no effect.

Specified by:
unregisterCacheWriter in interface Ehcache

getRegisteredCacheWriter

public CacheWriter getRegisteredCacheWriter()
Retrieves the CacheWriter that was registered for this cache.

Specified by:
getRegisteredCacheWriter in interface Ehcache
Returns:
the registered CacheWriter; or null if none was registered before

getWithLoader

public Element getWithLoader(java.lang.Object key,
                             CacheLoader loader,
                             java.lang.Object loaderArgument)
                      throws CacheException
This method is not appropriate to use with BlockingCache.

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 - if this method is called

getAllWithLoader

public java.util.Map getAllWithLoader(java.util.Collection keys,
                                      java.lang.Object loaderArgument)
                               throws CacheException
This method is not appropriate to use with BlockingCache.

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 - if this method is called

load

public void load(java.lang.Object key)
          throws CacheException
This method is not appropriate to use with BlockingCache.

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 - if this method is called

loadAll

public void loadAll(java.util.Collection keys,
                    java.lang.Object argument)
             throws CacheException
This method is not appropriate to use with BlockingCache.

Specified by:
loadAll in interface Ehcache
Throws:
CacheException - if this method is called

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.

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()

registerCacheUsageListener

public void registerCacheUsageListener(CacheUsageListener cacheUsageListener)
                                throws java.lang.IllegalStateException
Registers a CacheUsageListener which will be notified of the cache usage. Implementations of CacheUsageListener should override the Object.equals(Object) and Object.hashCode() methods as it is used for equality check

Specified by:
registerCacheUsageListener in interface Ehcache
Throws:
java.lang.IllegalStateException

removeCacheUsageListener

public void removeCacheUsageListener(CacheUsageListener cacheUsageListener)
                              throws java.lang.IllegalStateException
Remove an already registered CacheUsageListener, if any. Depends on the Object.equals(Object) method.

Specified by:
removeCacheUsageListener in interface Ehcache
Throws:
java.lang.IllegalStateException

isStatisticsEnabled

public boolean isStatisticsEnabled()
Returns true if statistics collection is enabled

Specified by:
isStatisticsEnabled in interface Ehcache
Returns:
true if statistics is enabled, false otherwise

setStatisticsEnabled

public void setStatisticsEnabled(boolean enabledStatistics)
Enable/disable statistics collection. Enabling statistics does not have any effect on sampled statistics. To enable sampled statistics, use Ehcache.setSampledStatisticsEnabled(boolean) with parameter true. Disabling statistics also disables the sampled statistics collection if it is enabled

Specified by:
setStatisticsEnabled in interface Ehcache

getSampledCacheStatistics

public SampledCacheStatistics getSampledCacheStatistics()
Returns sampled statistics for this cache.

Specified by:
getSampledCacheStatistics in interface Ehcache
Returns:
The sampled cache statistics

setSampledStatisticsEnabled

public void setSampledStatisticsEnabled(boolean enabledStatistics)
Enable/disable sampled statistics collection. Enabling sampled statistics also enables the normal statistics collection if its not already enabled. Disabling sampled statistics does not have any effect on normal statistics.

Specified by:
setSampledStatisticsEnabled in interface Ehcache

isSampledStatisticsEnabled

public boolean isSampledStatisticsEnabled()
Returns if sampled statistics collection is enabled or disabled

Specified by:
isSampledStatisticsEnabled in interface Ehcache
Returns:
true if sampled statistics is enabled, false otherwise
See Also:
Ehcache.isSampledStatisticsEnabled()

getInternalContext

public java.lang.Object getInternalContext()
This should not be used return some internal context (generally will be null)

Specified by:
getInternalContext in interface Ehcache

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:
disableDynamicFeatures in interface Ehcache

isClusterCoherent

public boolean isClusterCoherent()
Returns 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:
isClusterCoherent in interface Ehcache
Returns:
true if the cache is in coherent mode cluster-wide, false otherwise

isNodeCoherent

public boolean isNodeCoherent()
Returns 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:
isNodeCoherent in interface Ehcache
Returns:
true if the cache is in coherent mode cluster-wide, false otherwise

setNodeCoherent

public void setNodeCoherent(boolean coherent)
Sets the cache in coherent or incoherent mode depending on the parameter on this node. Calling setNodeCoherent(true) when the cache is already in coherent mode or calling setNodeCoherent(false) when already in incoherent mode will be a no-op.

It applies to coherent clustering mechanisms only e.g. Terracotta

Specified by:
setNodeCoherent in interface Ehcache
Parameters:
coherent - true transitions to coherent mode, false to incoherent mode

waitUntilClusterCoherent

public void waitUntilClusterCoherent()
This method waits until the cache is in coherent mode in all the connected nodes. If the cache is already in coherent mode it returns immediately

It applies to coherent clustering mechanisms only e.g. Terracotta

Specified by:
waitUntilClusterCoherent in interface Ehcache

setTransactionManagerLookup

public void setTransactionManagerLookup(TransactionManagerLookup transactionManagerLookup)
This class is used to access the transaction manager used during XA.

Specified by:
setTransactionManagerLookup in interface Ehcache

ehcache

true