ehcache

net.sf.ehcache
Class Cache

java.lang.Object
  extended bynet.sf.ehcache.Cache
All Implemented Interfaces:
java.lang.Cloneable

public class Cache
extends java.lang.Object
implements java.lang.Cloneable

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

Version:
$Id: Cache.java,v 1.36 2004/11/07 12:54:41 gregluck Exp $
Author:
Greg Luck

Field Summary
static java.lang.String DEFAULT_CACHE_NAME
          A reserved word for cache names.
static int STATUS_ALIVE
          The cache is alive.
static int STATUS_DISPOSED
          The cache is uninitialised.
static int STATUS_UNINITIALISED
          The cache is uninitialised.
 
Constructor Summary
Cache(java.lang.String name, int maximumSize, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds)
          Constructor.
Cache(java.lang.String name, int maximumSize, boolean overflowToDisk, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent, long diskExpiryThreadIntervalSeconds)
          Full Constructor.
 
Method Summary
 long calculateInMemorySize()
          Gets the size of the memory store for this cache

Warning: This method can be very expensive to run.

 java.lang.Object clone()
          Clones a cache.
(package private)  void dispose()
          Flushes all cache items from memory to auxilliary caches and close the auxilliary caches.
 Element get(java.io.Serializable key)
          Gets an element from the cache.
 long getDiskExpiryThreadIntervalSeconds()
           
(package private)  DiskStore getDiskStore()
          Gets the internal DiskStore.
 int getDiskStoreHitCount()
          Number of times a requested item was found in the Disk Store
 int getDiskStoreSize()
          Returns the number of elements in the disk store.
 int getHitCount()
          Number of times a requested item was found in the cache
 java.util.List getKeys()
          Returns a list of all elements 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 elements in the cache.
 int getMaxElementsInMemory()
          Gets the maximum number of elements to hold in memory
(package private)  MemoryStore getMemoryStore()
          Gets the internal MemoryStore.
 int getMemoryStoreHitCount()
          Number of times a requested item was found in the Memory Store
 long getMemoryStoreSize()
          Returns the number of elements in the memory store.
 int getMissCountExpired()
          Number of times a requested element was found but was expired
 int getMissCountNotFound()
          Number of times a requested element was not found in the cache.
 java.lang.String getName()
          Gets the cache name
 Element getQuiet(java.io.Serializable key)
          Gets an element from the cache, without updating Element statistics.
 int getSize()
          Gets the size of the cache.
 int getStatus()
          Gets the status attribute of the Store object
 long getTimeToIdleSeconds()
          Gets timeToIdleSeconds
 long getTimeToLiveSeconds()
          Gets timeToLiveSeconds
(package private)  void initialise(Configuration configuration)
          Newly created caches do not have a MemoryStore or a DiskStore.
 boolean isDiskPersistent()
           
 boolean isEternal()
          Are elements eternal
 boolean isExpired(Element element)
          Checks whether this cache element has expired.
 boolean isOverflowToDisk()
          Does the overflow go to disk
 void put(Element element)
          Put an element in the cache.
 void putQuiet(Element element)
          Put an element in the cache, without updating statistics.
 boolean remove(java.io.Serializable key)
          Removes an Element from the Cache.
 void removeAll()
          Removes all cached items.
(package private)  void setName(java.lang.String name)
          Sets the name
 java.lang.String toString()
          Returns a String representation of Cache
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, 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

STATUS_UNINITIALISED

public static final int STATUS_UNINITIALISED
The cache is uninitialised. It cannot be used.

See Also:
Constant Field Values

STATUS_ALIVE

public static final int STATUS_ALIVE
The cache is alive. It can be used.

See Also:
Constant Field Values

STATUS_DISPOSED

public static final int STATUS_DISPOSED
The cache is uninitialised. It cannot be used.

See Also:
Constant Field Values
Constructor Detail

Cache

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

The Configurator 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.


Cache

public Cache(java.lang.String name,
             int maximumSize,
             boolean overflowToDisk,
             boolean eternal,
             long timeToLiveSeconds,
             long timeToIdleSeconds,
             boolean diskPersistent,
             long diskExpiryThreadIntervalSeconds)
Full Constructor.

The Configurator 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.

Method Detail

initialise

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

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


put

public void put(Element element)
         throws java.lang.IllegalArgumentException,
                java.lang.IllegalStateException
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.

Parameters:
element -
Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE
java.lang.IllegalArgumentException - if the element is null

putQuiet

public void putQuiet(Element element)
              throws java.lang.IllegalArgumentException,
                     java.lang.IllegalStateException
Put an element in the cache, without updating statistics. This is meant to be used in conjunction with getQuiet(java.io.Serializable)

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.

Parameters:
element -
Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE
java.lang.IllegalArgumentException - if the element is null

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(java.io.Serializable) to peak into the Element to see its last access time with get

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

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_ALIVE
CacheException
See Also:
isExpired(net.sf.ehcache.Element)

getKeys

public java.util.List getKeys()
                       throws java.lang.IllegalStateException,
                              CacheException
Returns a list of all elements 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.

Returns:
a list of Serializable keys
Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE
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 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.

Returns:
a list of Serializable keys
Throws:
java.lang.IllegalStateException - if the cache is not 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

Returns:
a list of Serializable keys
Throws:
java.lang.IllegalStateException - if the cache is not 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.

Parameters:
key -
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_ALIVE

removeAll

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

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE
java.io.IOException

dispose

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.

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

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.

Returns:
The size value
Throws:
java.lang.IllegalStateException - if the cache is not 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

Returns:
the 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.

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getDiskStoreSize

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

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getStatus

public int getStatus()
Gets the status attribute of the Store object

Returns:
The status value

getHitCount

public int getHitCount()
                throws java.lang.IllegalStateException
Number of times a requested item was found in the cache

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getMemoryStoreHitCount

public int getMemoryStoreHitCount()
                           throws java.lang.IllegalStateException
Number of times a requested item was found in the Memory Store

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getDiskStoreHitCount

public int getDiskStoreHitCount()
                         throws java.lang.IllegalStateException
Number of times a requested item was found in the Disk Store

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getMissCountNotFound

public int getMissCountNotFound()
                         throws java.lang.IllegalStateException
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.

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getMissCountExpired

public int getMissCountExpired()
                        throws java.lang.IllegalStateException
Number of times a requested element was found but was expired

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getName

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


setName

void setName(java.lang.String name)
Sets the name


getTimeToIdleSeconds

public long getTimeToIdleSeconds()
Gets timeToIdleSeconds


getTimeToLiveSeconds

public long getTimeToLiveSeconds()
Gets timeToLiveSeconds


isEternal

public boolean isEternal()
Are elements eternal


isOverflowToDisk

public boolean isOverflowToDisk()
Does the overflow go to disk


getMaxElementsInMemory

public int getMaxElementsInMemory()
Gets the maximum number of elements to hold in memory


toString

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


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.

Returns:
true if it has expired
Throws:
java.lang.IllegalStateException - if the cache is not 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.

Returns:
an object of type Cache
Throws:
java.lang.CloneNotSupportedException

getDiskStore

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

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

getMemoryStore

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

Throws:
java.lang.IllegalStateException - if the cache is not STATUS_ALIVE

isDiskPersistent

public boolean isDiskPersistent()
Returns:
true if the cache overflows to disk and the disk is persistent between restarts

getDiskExpiryThreadIntervalSeconds

public long getDiskExpiryThreadIntervalSeconds()
Returns:
the interval between runs of the expiry thread, where it checks the disk store for expired elements. It is not the the timeToLiveSeconds.

ehcache