General Ehcache
How do you get an element without affecting statistics?
Use the Cache.getQuiet() method. It returns an element without updating statistics.
Is there a simple way to disable Ehcache when testing?
Set the system property net.sf.ehcache.disabled=true to disable Ehcache. This can easily be done using -Dnet.sf.ehcache.disabled=true in the command line. If Ehcache is disabled, no elements will be added to a cache.
How do I dynamically change cache attributes at runtime?
This is not possible. However, you can achieve the same result as follows:
1. Create a new cache:
Cache cache = new Cache("test2", 1, true, true, 0, 0, true, 120, ...);
cacheManager.addCache(cache);
See the Javadoc for the full parameters.
2. Get a list of keys using cache.getKeys(), then get each element and put it in the new cache.
None of this will use much memory because the new cache elements have values that reference the same data as the original cache.
3. Use the cacheManager.removeCache("oldcachename") method to remove the original cache.
Do you need to call CacheManager.getInstance().shutdown() when you finish with Ehcache?
Yes, it is recommended. If the JVM keeps running after you stop using Ehcache, you should call CacheManager.getInstance().shutdown() so that the threads are stopped and cache memory is released back to the JVM. However, if the CacheManager does not get shut down, it should not be a problem. There is a shutdown hook which calls the shutdown on JVM exit. For additional information, see
Shutting Down Ehcache.
Can you use Ehcache after a CacheManager.shutdown()?
Yes. When you call CacheManager.shutdown() is sets the singleton in CacheManager to null. If you try an use a cache after this you will get a CacheException. You need to call CacheManager.create(). It will create a brand new one good to go. Internally the CacheManager singleton gets set to the new one. So you can create and shutdown as many times as you like. There is a test which explicitly confirms this behavior. See CacheManagerTest#testCreateShutdownCreate().
Why are statistics counters showing 0 for active caches?
Statistics gathering is disabled by default in order to optimize performance. You can enable statistics gathering in caches in one of the following ways:
In cache configuration by adding
statistics="true" to the
<cache> element.
Programmatically when setting a cache's configuration.
How do I detect deadlocks in Ehcache?
Ehcache does not experience deadlocks. However, deadlocks in your application code can be detected with certain tools, such as JConsole.