ehcache

net.sf.ehcache
Class CacheManager

java.lang.Object
  extended by net.sf.ehcache.CacheManager

public class CacheManager
extends java.lang.Object

A container for Ehcaches that maintain all aspects of their lifecycle.

CacheManager may be either be a singleton if created with factory methods, or multiple instances may exist, in which case resources required by each must be unique.

A CacheManager holds references to Caches and Ehcaches and manages their creation and lifecycle.

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

Field Summary
static java.util.List<CacheManager> ALL_CACHE_MANAGERS
          Keeps track of all known CacheManagers.
protected  CacheManagerEventListenerRegistry cacheManagerEventListenerRegistry
          The listener registry
protected  java.util.Map<java.lang.String,CacheManagerPeerListener> cacheManagerPeerListeners
          The map of listeners
protected  java.util.Map<java.lang.String,CacheManagerPeerProvider> cacheManagerPeerProviders
          The map of providers
protected  java.util.Map caches
          Caches managed by this manager.
protected  java.util.Map ehcaches
          Ehcaches managed by this manager.
static java.lang.String ENABLE_SHUTDOWN_HOOK_PROPERTY
          System property to enable creation of a shutdown hook for CacheManager.
protected  java.lang.String name
          A name for this CacheManager to distinguish it from others.
protected  java.lang.Thread shutdownHook
          The shutdown hook thread for CacheManager.
protected  Status status
          Status of the Cache Manager
 
Constructor Summary
CacheManager()
          Constructor.
CacheManager(Configuration configuration)
          An constructor for CacheManager, which takes a configuration object, rather than one created by parsing an ehcache.xml file.
CacheManager(java.io.InputStream configurationInputStream)
          An ordinary constructor for CacheManager.
CacheManager(java.lang.String configurationFileName)
          An ordinary constructor for CacheManager.
CacheManager(java.net.URL configurationURL)
          An ordinary constructor for CacheManager.
 
Method Summary
 void addCache(Cache cache)
          Adds a Cache to the CacheManager.
 void addCache(Ehcache cache)
          Adds an Ehcache to the CacheManager.
 void addCache(java.lang.String cacheName)
          Adds a Ehcache based on the defaultCache with the given name.
 boolean cacheExists(java.lang.String cacheName)
          Checks whether a cache of type ehcache exists.
protected  void checkStatus()
          Checks the state of the CacheManager for legal operation
 void clearAll()
          Clears the contents of all caches in the CacheManager, but without removing any caches.
 void clearAllStartingWith(java.lang.String prefix)
          Clears the contents of all caches in the CacheManager with a name starting with the prefix, but without removing them.
static CacheManager create()
          A factory method to create a singleton CacheManager with default config, or return it if it exists.
static CacheManager create(java.io.InputStream inputStream)
          A factory method to create a singleton CacheManager from a java.io.InputStream.
static CacheManager create(java.lang.String configurationFileName)
          A factory method to create a singleton CacheManager with a specified configuration.
static CacheManager create(java.net.URL configurationFileURL)
          A factory method to create a singleton CacheManager from an URL.
 CacheEventListener createTerracottaEventReplicator(Ehcache cache)
          Create/access the appropriate clustered cache event replicator for the given cache
 Store createTerracottaStore(Ehcache cache)
          Create/access the appropriate terracotta clustered store for the given cache
 WriteBehind createTerracottaWriteBehind(Ehcache cache)
          Create/access the appropriate clustered write behind queue for the given cache
 java.lang.String getActiveConfigurationText()
          Returns the active configuration text for this CacheManager
 java.lang.String getActiveConfigurationText(java.lang.String cacheName)
          Returns the active configuration text for the input cacheName
 Cache getCache(java.lang.String name)
          Returns a concrete implementation of Cache, it it is available in the CacheManager.
 CacheManagerEventListener getCacheManagerEventListener()
          Returns the composite listener.
 CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry()
          Gets the CacheManagerEventListenerRegistry.
 CacheManagerPeerProvider getCacheManagerPeerProvider(java.lang.String scheme)
          Gets the CacheManagerPeerProvider, matching the given scheme For distributed caches, the peer provider finds other cache managers and their caches in the same cluster
 java.lang.String[] getCacheNames()
          Returns a list of the current cache names.
 CacheManagerPeerListener getCachePeerListener(java.lang.String scheme)
          When CacheManage is configured as part of a cluster, a CacheManagerPeerListener will be registered in it.
 CacheCluster getCluster(ClusterScheme scheme)
          Returns access to information about the cache cluster.
 java.lang.String getClusterUUID()
          Returns unique cluster-wide id for this cache-manager.
 java.lang.String getDiskStorePath()
          Returns the disk store path.
 Ehcache getEhcache(java.lang.String name)
          Gets an Ehcache

static CacheManager getInstance()
          A factory method to create a singleton CacheManager with default config, or return it if it exists.
 java.lang.String getName()
          Gets the name of the CacheManager.
 java.lang.String getOriginalConfigurationText()
          Returns the original configuration text for this CacheManager
 java.lang.String getOriginalConfigurationText(java.lang.String cacheName)
          Returns the original configuration text for the input cacheName
 Status getStatus()
          Gets the status attribute of the Ehcache
 FailSafeTimer getTimer()
          Returns a FailSafeTimer associated with this CacheManager
 int hashCode()
          
protected  void init(Configuration configuration, java.lang.String configurationFileName, java.net.URL configurationURL, java.io.InputStream configurationInputStream)
          initialises the CacheManager
 boolean isNamed()
          Indicate whether the CacheManager is named or not.
 void removalAll()
          Removes all caches using removeCache(java.lang.String) for each cache.
 void removeCache(java.lang.String cacheName)
          Remove a cache from the CacheManager.
 void replaceCacheWithDecoratedCache(Ehcache ehcache, Ehcache decoratedCache)
          Replaces in the map of Caches managed by this CacheManager an Ehcache with a decorated version of the same Ehcache.
 void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener)
          Same as getCacheManagerEventListenerRegistry().registerListener(cacheManagerEventListener); Left for backward compatiblity
 void setName(java.lang.String name)
          Sets the name of the CacheManager.
 void shutdown()
          Shuts down the CacheManager.
 java.lang.String toString()
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

ALL_CACHE_MANAGERS

public static final java.util.List<CacheManager> ALL_CACHE_MANAGERS
Keeps track of all known CacheManagers. Used to check on conflicts. CacheManagers should remove themselves from this list during shut down.


ENABLE_SHUTDOWN_HOOK_PROPERTY

public static final java.lang.String ENABLE_SHUTDOWN_HOOK_PROPERTY
System property to enable creation of a shutdown hook for CacheManager.

See Also:
Constant Field Values

ehcaches

protected final java.util.Map ehcaches
Ehcaches managed by this manager.


caches

protected final java.util.Map caches
Caches managed by this manager. A Cache is also an Ehcache. For central managment the cache is also in the ehcaches map.


name

protected java.lang.String name
A name for this CacheManager to distinguish it from others.


status

protected Status status
Status of the Cache Manager


cacheManagerPeerProviders

protected java.util.Map<java.lang.String,CacheManagerPeerProvider> cacheManagerPeerProviders
The map of providers


cacheManagerPeerListeners

protected java.util.Map<java.lang.String,CacheManagerPeerListener> cacheManagerPeerListeners
The map of listeners


cacheManagerEventListenerRegistry

protected CacheManagerEventListenerRegistry cacheManagerEventListenerRegistry
The listener registry


shutdownHook

protected java.lang.Thread shutdownHook
The shutdown hook thread for CacheManager. This ensures that the CacheManager and Caches are left in a consistent state on a CTRL-C or kill.

This thread must be unregistered as a shutdown hook, when the CacheManager is disposed. Otherwise the CacheManager is not GC-able.

Of course kill -9 or abrupt termination will not run the shutdown hook. In this case, various sanity checks are made at start up.

Constructor Detail

CacheManager

public CacheManager(Configuration configuration)
             throws CacheException
An constructor for CacheManager, which takes a configuration object, rather than one created by parsing an ehcache.xml file. This constructor gives complete control over the creation of the CacheManager.

Care should be taken to ensure that, if multiple CacheManages are created, they do now overwrite each others disk store files, as would happend if two were created which used the same diskStore path.

This method does not act as a singleton. Callers must maintain their own reference to it.

Note that if one of the create() methods are called, a new singleton instance will be created, separate from any instances created in this method.

Parameters:
configuration -
Throws:
CacheException

CacheManager

public CacheManager(java.lang.String configurationFileName)
             throws CacheException
An ordinary constructor for CacheManager. This method does not act as a singleton. Callers must maintain a reference to it. Note that if one of the create() methods are called, a new singleton will be created, separate from any instances created in this method.

Parameters:
configurationFileName - an xml configuration file available through a file name. The configuration File is created using new File(configurationFileName)
Throws:
CacheException
See Also:
create(String)

CacheManager

public CacheManager(java.net.URL configurationURL)
             throws CacheException
An ordinary constructor for CacheManager. This method does not act as a singleton. Callers must maintain a reference to it. Note that if one of the create() methods are called, a new singleton will be created, separate from any instances created in this method.

This method can be used to specify a configuration resource in the classpath other than the default of \"/ehcache.xml\":

 URL url = this.getClass().getResource("/ehcache-2.xml");
 
Note that Class.getResource(java.lang.String) will look for resources in the same package unless a leading "/" is used, in which case it will look in the root of the classpath.

You can also load a resource using other class loaders. e.g. Thread.getContextClassLoader()

Parameters:
configurationURL - an xml configuration available through a URL.
Throws:
CacheException
Since:
1.2
See Also:
create(java.net.URL)

CacheManager

public CacheManager(java.io.InputStream configurationInputStream)
             throws CacheException
An ordinary constructor for CacheManager. This method does not act as a singleton. Callers must maintain a reference to it. Note that if one of the create() methods are called, a new singleton will be created, separate from any instances created in this method.

Parameters:
configurationInputStream - an xml configuration file available through an inputstream
Throws:
CacheException
See Also:
create(java.io.InputStream)

CacheManager

public CacheManager()
             throws CacheException
Constructor.

Throws:
CacheException
Method Detail

init

protected void init(Configuration configuration,
                    java.lang.String configurationFileName,
                    java.net.URL configurationURL,
                    java.io.InputStream configurationInputStream)
initialises the CacheManager


getClusterUUID

public java.lang.String getClusterUUID()
Returns unique cluster-wide id for this cache-manager. Only applicable when running in "cluster" mode, e.g. when this cache-manager contains caches clustered with Terracotta. Otherwise returns blank string.

Returns:
Returns unique cluster-wide id for this cache-manager when it contains clustered caches (e.g. Terracotta clustered caches). Otherwise returns blank string.

createTerracottaStore

public Store createTerracottaStore(Ehcache cache)
Create/access the appropriate terracotta clustered store for the given cache

Parameters:
cache - The cache for which the Store should be created
Returns:
a new (or existing) clustered store

createTerracottaWriteBehind

public WriteBehind createTerracottaWriteBehind(Ehcache cache)
Create/access the appropriate clustered write behind queue for the given cache

Parameters:
cache - The cache for which the write behind queue should be created
Returns:
a new (or existing) write behind queue

createTerracottaEventReplicator

public CacheEventListener createTerracottaEventReplicator(Ehcache cache)
Create/access the appropriate clustered cache event replicator for the given cache

Parameters:
cache - The cache for which the clustered event replicator should be created
Returns:
a new cache event replicator

create

public static CacheManager create()
                           throws CacheException
A factory method to create a singleton CacheManager with default config, or return it if it exists.

The configuration will be read, Ehcaches created and required stores initialized. When the CacheManager is no longer required, call shutdown to free resources.

Returns:
the singleton CacheManager
Throws:
CacheException - if the CacheManager cannot be created

getInstance

public static CacheManager getInstance()
                                throws CacheException
A factory method to create a singleton CacheManager with default config, or return it if it exists.

This has the same effect as create()

Same as create()

Returns:
the singleton CacheManager
Throws:
CacheException - if the CacheManager cannot be created

create

public static CacheManager create(java.lang.String configurationFileName)
                           throws CacheException
A factory method to create a singleton CacheManager with a specified configuration.

Parameters:
configurationFileName - an xml file compliant with the ehcache.xsd schema

The configuration will be read, Ehcaches created and required stores initialized. When the CacheManager is no longer required, call shutdown to free resources.

Throws:
CacheException

create

public static CacheManager create(java.net.URL configurationFileURL)
                           throws CacheException
A factory method to create a singleton CacheManager from an URL.

This method can be used to specify a configuration resource in the classpath other than the default of \"/ehcache.xml\": This method can be used to specify a configuration resource in the classpath other than the default of \"/ehcache.xml\":

 URL url = this.getClass().getResource("/ehcache-2.xml");
 
Note that Class.getResource(java.lang.String) will look for resources in the same package unless a leading "/" is used, in which case it will look in the root of the classpath.

You can also load a resource using other class loaders. e.g. Thread.getContextClassLoader()

Parameters:
configurationFileURL - an URL to an xml file compliant with the ehcache.xsd schema

The configuration will be read, Ehcaches created and required stores initialized. When the CacheManager is no longer required, call shutdown to free resources.

Throws:
CacheException

create

public static CacheManager create(java.io.InputStream inputStream)
                           throws CacheException
A factory method to create a singleton CacheManager from a java.io.InputStream.

This method makes it possible to use an inputstream for configuration. Note: it is the clients responsibility to close the inputstream.

Parameters:
inputStream - InputStream of xml compliant with the ehcache.xsd schema

The configuration will be read, Ehcaches created and required stores initialized. When the CacheManager is no longer required, call shutdown to free resources.

Throws:
CacheException

getCache

public Cache getCache(java.lang.String name)
               throws java.lang.IllegalStateException,
                      java.lang.ClassCastException
Returns a concrete implementation of Cache, it it is available in the CacheManager. Consider using getEhcache(String name) instead, which will return decorated caches that are registered.

If a decorated ehcache is registered in CacheManager, an undecorated Cache with the same name will also exist.

Returns:
a Cache, if an object of that type exists by that name, else null
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE
java.lang.ClassCastException
See Also:
getEhcache(String)

getEhcache

public Ehcache getEhcache(java.lang.String name)
                   throws java.lang.IllegalStateException
Gets an Ehcache

Returns:
a Cache, if an object of type Cache exists by that name, else null
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

addCache

public void addCache(java.lang.String cacheName)
              throws java.lang.IllegalStateException,
                     ObjectExistsException,
                     CacheException
Adds a Ehcache based on the defaultCache with the given name.

Memory and Disk stores will be configured for it and it will be added to the map of caches.

Also notifies the CacheManagerEventListener after the cache was initialised and added.

It will be created with the defaultCache attributes specified in ehcache.xml

Parameters:
cacheName - the name for the cache
Throws:
ObjectExistsException - if the cache already exists
CacheException - if there was an error creating the cache.
java.lang.IllegalStateException

addCache

public void addCache(Cache cache)
              throws java.lang.IllegalStateException,
                     ObjectExistsException,
                     CacheException
Adds a Cache to the CacheManager.

Memory and Disk stores will be configured for it and it will be added to the map of caches. Also notifies the CacheManagerEventListener after the cache was initialised and added.

Parameters:
cache -
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_UNINITIALISED before this method is called.
ObjectExistsException - if the cache already exists in the CacheManager
CacheException - if there was an error adding the cache to the CacheManager

addCache

public void addCache(Ehcache cache)
              throws java.lang.IllegalStateException,
                     ObjectExistsException,
                     CacheException
Adds an Ehcache to the CacheManager.

Memory and Disk stores will be configured for it and it will be added to the map of caches. Also notifies the CacheManagerEventListener after the cache was initialised and added.

Parameters:
cache -
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_UNINITIALISED before this method is called.
ObjectExistsException - if the cache already exists in the CacheManager
CacheException - if there was an error adding the cache to the CacheManager

cacheExists

public boolean cacheExists(java.lang.String cacheName)
                    throws java.lang.IllegalStateException
Checks whether a cache of type ehcache exists.

Parameters:
cacheName - the cache name to check for
Returns:
true if it exists
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

removalAll

public void removalAll()
Removes all caches using removeCache(java.lang.String) for each cache.


removeCache

public void removeCache(java.lang.String cacheName)
                 throws java.lang.IllegalStateException
Remove a cache from the CacheManager. The cache is disposed of.

Parameters:
cacheName - the cache name
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

shutdown

public void shutdown()
Shuts down the CacheManager.

If the shutdown occurs on the singleton, then the singleton is removed, so that if a singleton access method is called, a new singleton will be created.

By default there is no shutdown hook (ehcache-1.3-beta2 and higher).

Set the system property net.sf.ehcache.enableShutdownHook=true to turn it on.


getCacheNames

public java.lang.String[] getCacheNames()
                                 throws java.lang.IllegalStateException
Returns a list of the current cache names.

Returns:
an array of Strings
Throws:
java.lang.IllegalStateException - if the cache is not Status.STATUS_ALIVE

checkStatus

protected void checkStatus()
Checks the state of the CacheManager for legal operation


getStatus

public Status getStatus()
Gets the status attribute of the Ehcache

Returns:
The status value from the Status enum class

clearAll

public void clearAll()
              throws CacheException
Clears the contents of all caches in the CacheManager, but without removing any caches.

This method is not synchronized. It only guarantees to clear those elements in a cache at the time that the Ehcache.removeAll() mehod on each cache is called.

Throws:
CacheException

clearAllStartingWith

public void clearAllStartingWith(java.lang.String prefix)
                          throws CacheException
Clears the contents of all caches in the CacheManager with a name starting with the prefix, but without removing them.

This method is not synchronized. It only guarantees to clear those elements in a cache at the time that the Ehcache.removeAll() method on each cache is called.

Parameters:
prefix - The prefix the cache name should start with
Throws:
CacheException
Since:
1.7.2

getCacheManagerPeerProvider

public CacheManagerPeerProvider getCacheManagerPeerProvider(java.lang.String scheme)
Gets the CacheManagerPeerProvider, matching the given scheme For distributed caches, the peer provider finds other cache managers and their caches in the same cluster

Parameters:
scheme - the replication scheme to use. Schemes shipped with ehcache are RMI, JGROUPS, JMS
Returns:
the provider, or null if one does not exist

getCachePeerListener

public CacheManagerPeerListener getCachePeerListener(java.lang.String scheme)
When CacheManage is configured as part of a cluster, a CacheManagerPeerListener will be registered in it. Use this to access the individual cache listeners

Parameters:
scheme - the replication scheme to use. Schemes shipped with ehcache are RMI, JGROUPS, JMS
Returns:
the listener, or null if one does not exist

getCacheManagerEventListener

public CacheManagerEventListener getCacheManagerEventListener()
Returns the composite listener. A notification sent to this listener will notify all registered listeners.

Returns:
null if none
See Also:
"getCacheManagerEventListenerRegistry"

setCacheManagerEventListener

public void setCacheManagerEventListener(CacheManagerEventListener cacheManagerEventListener)
Same as getCacheManagerEventListenerRegistry().registerListener(cacheManagerEventListener); Left for backward compatiblity

Parameters:
cacheManagerEventListener - the listener to set.
See Also:
"getCacheManagerEventListenerRegistry"

getCacheManagerEventListenerRegistry

public CacheManagerEventListenerRegistry getCacheManagerEventListenerRegistry()
Gets the CacheManagerEventListenerRegistry. Add and remove listeners here.


replaceCacheWithDecoratedCache

public void replaceCacheWithDecoratedCache(Ehcache ehcache,
                                           Ehcache decoratedCache)
                                    throws CacheException
Replaces in the map of Caches managed by this CacheManager an Ehcache with a decorated version of the same Ehcache. CacheManager can operate fully with a decorated Ehcache.

Ehcache Decorators can be used to obtain different behaviour from an Ehcache in a very flexible way. Some examples in ehcache are:

  1. BlockingCache - A cache that blocks other threads from getting a null element until the first thread has placed a value in it.
  2. SelfPopulatingCache - A BlockingCache that has the additional property of knowing how to load its own entries.
Many other kinds are possible.

It is generally required that a decorated cache, once constructed, is made available to other execution threads. The simplest way of doing this is to substitute the original cache for the decorated one here.

Note that any overwritten Ehcache methods will take on new behaviours without casting. Casting is only required for new methods that the decorator introduces. For more information see the well known Gang of Four Decorator pattern.

Parameters:
ehcache -
decoratedCache - An implementation of Ehcache that wraps the original cache.
Throws:
CacheException - if the two caches do not equal each other.

getName

public java.lang.String getName()
Gets the name of the CacheManager. This is useful for distinguishing multiple CacheManagers

Returns:
the name, or the output of toString() if it is not set.
See Also:
which uses either the name or Object.toString()

isNamed

public boolean isNamed()
Indicate whether the CacheManager is named or not.

Returns:
True if named

setName

public void setName(java.lang.String name)
Sets the name of the CacheManager. This is useful for distinguishing multiple CacheManagers in a monitoring situation.

Parameters:
name - a name with characters legal in a JMX ObjectName

toString

public java.lang.String toString()
Overrides:
toString in class java.lang.Object
Returns:
either the name of this CacheManager, or if unset, Object.toString()

getDiskStorePath

public java.lang.String getDiskStorePath()
Returns the disk store path. This may be null if no caches need a DiskStore and none was configured. The path cannot be changed after creation of the CacheManager. All caches take the disk store path from this value.

Returns:
the disk store path.

getTimer

public FailSafeTimer getTimer()
Returns a FailSafeTimer associated with this CacheManager

Returns:
The FailSafeTimer associated with this cache manager
Since:
1.7

getCluster

public CacheCluster getCluster(ClusterScheme scheme)
Returns access to information about the cache cluster.

Parameters:
scheme - The clustering scheme to retrieve information about (such as "Terracotta")
Returns:
Cluster API (never null, but possibly a simple single node implementation)
Since:
2.0
See Also:
ClusterScheme

getOriginalConfigurationText

public java.lang.String getOriginalConfigurationText()
Returns the original configuration text for this CacheManager

Returns:
Returns the original configuration text for this CacheManager

getActiveConfigurationText

public java.lang.String getActiveConfigurationText()
Returns the active configuration text for this CacheManager

Returns:
Returns the active configuration text for this CacheManager

getOriginalConfigurationText

public java.lang.String getOriginalConfigurationText(java.lang.String cacheName)
Returns the original configuration text for the input cacheName

Parameters:
cacheName -
Returns:
Returns the original configuration text for the input cacheName

getActiveConfigurationText

public java.lang.String getActiveConfigurationText(java.lang.String cacheName)
Returns the active configuration text for the input cacheName

Parameters:
cacheName -
Returns:
Returns the active configuration text for the input cacheName

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object

ehcache

true