Accessing cache provider’s CacheManager implementation

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

In all my previous post related to Caching, I gave examples where I was using 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 CacheManager 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.Factory;
5 import javax.cache.configuration.FactoryBuilder;
6 import javax.cache.configuration.MutableConfiguration;
7 import javax.cache.spi.CachingProvider;
8
9 import org.ehcache.Status;
10
11 public class JCacheDemo17 {
12 public static void main(String[] args) throws Exception {
13 CachingProvider cachingProvider = Caching.getCachingProvider();
14 CacheManager cacheManager = cachingProvider.getCacheManager();
15
16 Factory customExpiryPolicyfactory = FactoryBuilder.factoryOf(CustomTouchedExpiryPolicy.class);
17
18 MutableConfiguration mutableConfiguration = new MutableConfiguration();
19 mutableConfiguration.setTypes(String.class, String.class);
20 mutableConfiguration.setExpiryPolicyFactory(customExpiryPolicyfactory);
21
22 Cache cache = cacheManager.createCache("cache1", mutableConfiguration);
23 cache.put("key1", "value1");
24 cache.put("key2", "value2");
25 cache.put("key3", "value3");
26 cache.put("key4", "value4");
27
28 org.ehcache.CacheManager ehCacheManager = cacheManager.unwrap(org.ehcache.CacheManager.class);
29 Status status = ehCacheManager.getStatus();
30
31 System.out.println(status);
32
33 cachingProvider.close();
34 }
35 }

Explanation

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

The unwrap method returns Ehcache specific CacheManager implementation.

At line 29 we access Ehcache CacheManager specific method named “getStatus” and print the status at line 31.

Leave a Reply