This post explains two ways provided by JCache api through, which we can replace the values of existing cache entry.
JCache provides two apis for replacing the cache entry
1) replace(key, newValue)
–> This api replaces an entry with matching key given in the method argument with newValue. It returns true when replaced else false.
2) replace(key, oldValue, newValue)
–> This api replaces an entry’s value only if their is a entry with matching key and oldValue. If found the entry’s value is replaced with newValue. This api returns true when replaced else false.
Main Code
import java.util.Iterator;
import javax.cache.Cache;
import javax.cache.Cache.Entry;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
public class JCacheDemo2 {
public static void main(String[] args) {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
MutableConfiguration mutableConfiguration = new MutableConfiguration();
mutableConfiguration.setTypes(String.class, String.class);
Cache cache = cacheManager.createCache("cache1", mutableConfiguration);
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
cache.put("key4", "value4");
Iterator iterator = cache.iterator();
while(iterator.hasNext()) {
Entry entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("-----------1st way of replace------------");
cache.replace("key4", "value5");
iterator = cache.iterator();
while(iterator.hasNext()) {
Entry entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("----------2nd way of replace-------------");
cache.replace("key4", "value5", "value6");
iterator = cache.iterator();
while(iterator.hasNext()) {
Entry entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
cachingProvider.close();
}
}
Output
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
key2:value2
key1:value1
key4:value4
key3:value3
———–1st way of replace————
key2:value2
key1:value1
key4:value5
key3:value3
———-2nd way of replace————-
key2:value2
key1:value1
key4:value6
key3:value3