Different ways to add entry in cache

This post explains the different ways provided by JCache to add entries in a cache. The api’s are as mentioned below
1) void put(K key, V value) –> Takes key and value as argument
2) void putAll(Map map) –> Takes a map as an argument
3) boolean putIfAbsent(K key, V value) –> Takes a key and value, and add them only if the key doesn’t exist in the cache.

The below code gives you an example

Main Code


1  import java.util.HashMap;
2  import java.util.Iterator;
3  import java.util.Map;
4  
5  import javax.cache.Cache;
6  import javax.cache.Cache.Entry;
7  import javax.cache.CacheManager;
8  import javax.cache.Caching;
9  import javax.cache.configuration.MutableConfiguration;
10 import javax.cache.spi.CachingProvider;
11 
12 public class JCacheDemo4 {
13  public static void main(String[] args) {
14      CachingProvider cachingProvider = Caching.getCachingProvider();
15      CacheManager cacheManager = cachingProvider.getCacheManager();
16      
17      MutableConfiguration mutableConfiguration = new MutableConfiguration();
18      mutableConfiguration.setTypes(String.class, String.class);
19      mutableConfiguration.setStatisticsEnabled(true);
20      
21      Cache cache = cacheManager.createCache("cache1", mutableConfiguration);
22      cache.put("key1", "value1");
23      
24      Map map = new HashMap();
25      map.put("key2", "value2");
26      map.put("key3", "value3");
27      map.put("key4", "value4");
28      cache.putAll(map);
29      
30      cache.putIfAbsent("key5", "value5");
31      cache.putIfAbsent("key5", "value6");
32      
33      Iterator<Entry> iterator = cache.iterator();
34      while(iterator.hasNext()) {
35          Entry entry = iterator.next();
36          System.out.println(entry.getKey() + ":" + entry.getValue());
37      }
38      
39      cachingProvider.close();
40  }
41 }

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
key5:value5
key3:value3

Explanation

As you can see from the output and code that key1 is added using the first put api. key2, key3, and key4 is added using the second put api. key5 is added using putIfAbsent. The putIfAbsent is called twice as shown at line 30 and 31. On first call key5 is added since key5 doesn't exist and on second call it is not added since key5 already exist.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s