Tuesday 28 June 2022

Ehcache: replace: Replace the entry when the entry is not expired

org.ehcache.Cache#replace method replaces the entry for a key only if currently mapped to some value and the entry is not expired.

 

Signature

V replace(K key, V value) throws CacheLoadingException, CacheWritingException;

This logic is equivalent to below code snippet.

V oldValue = cache.get(key);
if (oldValue != null) {
	cache.put(key, value);
}
return oldValue;

Find the below working application.

 

CacheReplaceDemo.java

package com.sample.app;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.ehcache.Cache;
import org.ehcache.Cache.Entry;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;

public class CacheReplaceDemo {

	private static void printAllElementsFromCache(Cache<Long, String> empCache) {
		System.out.println("\nPrint all the elements from the cache");

		Iterator<Entry<Long, String>> iter = empCache.iterator();

		while (iter.hasNext()) {
			Entry<Long, String> entry = iter.next();
			System.out.println(entry.getKey() + " is mapped to (" + entry.getValue() + ")");
		}

	}

	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());

		Map<Long, String> dataMap = new HashMap<>();
		dataMap.put(1L, "Ram,34");
		dataMap.put(2L, "Krishna,38");
		dataMap.put(3L, "Ravi,41");
		empCache.putAll(dataMap);

		printAllElementsFromCache(empCache);

		System.out.println("\nReplace elements with keys 1 amd 5");
		empCache.replace(1L, "Rama Krishna, 41");
		empCache.replace(5L, "Rama Krishna, 41");

		printAllElementsFromCache(empCache);

	}

}

Output

Print all the elements from the cache
1 is mapped to (Ram,34)
2 is mapped to (Krishna,38)
3 is mapped to (Ravi,41)

Replace elements with keys 1 amd 5

Print all the elements from the cache
1 is mapped to (Rama Krishna, 41)
2 is mapped to (Krishna,38)
3 is mapped to (Ravi,41)




 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment