I want to clear the cache using JAVA code.
and for this goal I write this code:
public void clearCache(){
CacheManager.getInstance().clearAll();
}
is this code correct? and is there a way to confirm that it works good? thanks
Yes, your code cleares all caches you have in your cacheManager.
The ehcache-documentation says:void clearAll()
Clears the contents of all caches in the CacheManager, but without removing any caches
If you want to test it, you can add some elements to your cache, call clearCache()
and then try to get the values. The get()
-method should only return null
.
You can't add values directly in your cacheManager, it just manages the caches you declared in your configuration file. (by default it's ehcache.xml, you can get that on the ehcache homepage.) You also can add caches programmatically, even without knowing anything about the configuration.
CacheManager cacheManager = CacheManager.getInstance();
Ehcache cache = new Cache(cacheManager.getConfiguration().getDefaultCacheConfiguration());
cache.setName("cacheName");
cacheManager.addCache(cache);
To add a value to the cache you have to make an Element:
Element element = new Element(key, value)
and simply call cache.put(element)
.
If your cache-variable isn't visible anymore, but your cacheManager is, you can do the same with cacheManager.getCache(cacheName).put(element)
I hope this helps...