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
To empty the entire cache, use Cache. removeAll() . If the cache itself is removed ( Cache. dispose() or CacheManager.
Open Eclipse and navigate to the Window > Preferences. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. 3. Click the Clear Cached Files button in the File Cache window.
Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.
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...
If you know the cache name, you can retrieve it from the CacheManager and use removeAll().
CacheManager manager = CacheManager.getInstance();
Ehcache cache = manager.getCache(cacheName);
cache.removeAll();
Your approach works, but it will clear all caches' objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With