I want to do something with ehcache in Java that I think should be extremely simple, but I\'ve spent enough time frustrating myself with the docs...
Write a
I think you should remove the manager.cacheExists(..)
test and simply create your cache using testCache = manager.getCache("test");
instead of using new Cache(..)
. Even if your cache is diskPersistent, it won't exist until you get it the first time. (At least that's what I think as I'm only using getCache(..)
and it does exactly what you are looking for)
Note:
You could also add something like this to make sure the cache exists:
Cache cache = manager.getCache(name);
if (cache == null) {
throw new NullPointerException(String.format("no cache with name %s defined, please configure it in %s", name, url));
}
Note 2:
If your configuration file is called ehcache.xml, you shouldn't use I think I've confused using CacheManager.create(url)
. Instead use the CacheManager singleton:CacheManager.create(url)
with and using new CacheManager(url)
. Still, you should use the singleton for ehcache.xml
and new CacheManager(url)
for anything else.
// ehcache.xml - shared between different invocations
CacheManager defaultManager = CacheManager.getInstance();
// others - avoid calling twice with same argument
CacheManager manager = CacheManager.create(url);
Using CacheManager.create(..)
is problematic as it might completely ignore the passed URL if any of the create(..)
methods or getInstance()
have been called before:
public static CacheManager create(URL configurationFileURL) throws CacheException {
synchronized (CacheManager.class) {
if (singleton == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating new CacheManager with config URL: " + configurationFileURL);
}
singleton = new CacheManager(configurationFileURL);
}
return singleton;
}
}
That's why I wouldn't recommend using any of the CacheManager.create(..)
methods. Use CacheManager.getInstance()
or new CacheManager(url)
.