org.ehcache.Cache#remove method removes the value, if any, associated with the provided key.
Signature
void remove(K key) throws CacheWritingException;
Example
empCache.remove(2l);
Find the below working application.
CacheRemoveEntryFromCache.java
package com.sample.app;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
public class CacheRemoveEntryFromCache {
private static void printElementsFromCache(Cache<Long, String> empCache, Set<Long> keys) {
System.out.println("Elements in the cache are:");
Map<Long, String> map = empCache.getAll(keys);
for (Long key : map.keySet()) {
System.out.println(key + " is mapped to (" + map.get(key) + ")");
}
}
public static void main(String[] args) {
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);
Cache<Long, String> empCache = cacheManager.createCache("empCache", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());
empCache.put(1L, "Ram,34");
empCache.put(2L, "Krishna,38");
// Print entries in the cache
Set<Long> keys = new HashSet<>();
keys.add(1L);
keys.add(2L);
printElementsFromCache(empCache, keys);
System.out.println("\nRemove the element with key 2\n");
empCache.remove(2l);
printElementsFromCache(empCache, keys);
cacheManager.close();
}
}
Output
Elements in the cache are: 1 is mapped to (Ram,34) 2 is mapped to (Krishna,38) Remove the element with key 2 Elements in the cache are: 1 is mapped to (Ram,34) 2 is mapped to (null)
Previous Next Home
No comments:
Post a Comment