Accessing cache provider’s Cache implementation

This post explains how to access the cache provider’s Cache implementation through java cache api.

In all my previous post related to Caching, I gave examples where I was accessing cache provider for caching functionality through the Java Cache API.

The java cache api is set of specifications, which are implemented by cache providers and client access the cache providers through these apis.

The advantage of this approach is that client can easily jump from one cache provider to another without any code changes.

In our new example, we will be using Ehcache as the cache provider and access Ehcache specific Cache through java cache api.

Main Code


1  import javax.cache.Cache;
2  import javax.cache.CacheManager;
3  import javax.cache.Caching;
4  import javax.cache.configuration.MutableConfiguration;
5  import javax.cache.spi.CachingProvider;
6  
7  public class JCacheDemo13 {
8   public static void main(String[] args) {
9       CachingProvider cachingProvider = Caching.getCachingProvider();
10      CacheManager cacheManager = cachingProvider.getCacheManager();
11      
12      MutableConfiguration mutableConfiguration = new MutableConfiguration();
13      
14      Cache cache = cacheManager.createCache("cache1", mutableConfiguration);
15      cache.put("key1", "value1");
16      cache.put("key2", "value2");
17      cache.put("key3", "value3");
18      cache.put("key4", "value4");
19 
20      net.sf.ehcache.Cache ehCache = cache.unwrap(net.sf.ehcache.Cache.class);
21      System.out.println(ehCache.get("key1"));
22  }
23 }

Explanation

At line 20 we call “unwrap” method passing the class information of Ehcache specific Cache class as an argument.

The unwrap method returns Ehcache specific Cache implementation.

At line 21 we access the cache using the get method and print it.

Leave a Reply