1. Overview
Simply put, JCache is the standard caching API for Java. In this tutorial, we’re going to see what JCache is and how we can use it.
2. Maven Dependencies
To use JCache, we need to add the following dependency to our pom.xml:
<dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.0.0-PFD</version> </dependency>
Note that we can find the latest version of the library in the Maven Central Repository.
We also need to add an implementation of the API to our pom.xml; we’ll use Hazelcast here:
<dependency> <groupId>com.hazelcast</groupId> <artifactId>hazelcast</artifactId> <version>3.9-EA</version> </dependency>
We can also find the latest version of Hazelcast at its Maven Central Repository.
3. JCache Implementations
JCache is implemented by various caching solutions:
- JCache Reference Implementation
- Hazelcast
- Oracle Coherence
- Terracotta Ehcache
- Infinispan
Note that, unlike other reference implementations, it’s not recommended to use JCache Reference Implementation in production since it causes some concurrency issues.
4. Main Components
4.1. Cache
The Cache interface has the following useful methods:
- get() – takes the key of an element as a parameter and returns the value of the element; it returns null if the key does not exist in the Cache
- getAll() – multiple keys can be passed to this method as a Set; the method returns the given keys and associated values as a Map
- getAndRemove() – the method retrieves a value using its key and removes the element from the Cache
- put() – inserts a new item in the Cache
- clear() – removes all elements in the Cache
- containsKey() – checks if a Cache contains a particular key
As we can see, the methods’ names are pretty much self-explanatory. For more information on these methods and other ones, visit the Javadoc.
4.2. CacheManager
CacheManager is one of the most important interfaces of the API. It enables us to establish, configure and close Caches.
4.3. CachingProvider
CachingProvider is an interface which allows us to create and manage the lifecycle of CacheManagers.
4.4. Configuration
Configuration is an interface that enables us to configure Caches. It has one concrete implementation – MutableConfiguration and a subinterface – CompleteConfiguration.
5. Creating a Cache
Let’s see how we can create a simple Cache:
CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<String, String> config = new MutableConfiguration<>(); Cache<String, String> cache = cacheManager .createCache("simpleCache", config); cache.put("key1", "value1"); cache.put("key2", "value2"); cacheManager.close();
All we’re doing is:
- Creating a CachingProvider object, which we are using to construct a CacheManager object
- Creating a MutableConfiguration object, which is an implementation of the Configuration interface
- Creating a Cache object using the CacheManager object we created earlier
- Putting all the entries, we need to cache into our Cache object
- Closing the CacheManager to release the resources used by the Cache
If we do not provide any implementation of JCache in our pom.xml, the following exception will be thrown:
javax.cache.CacheException: No CachingProviders have been configured
The reason for this is that the JVM could not find any concrete implementation of the getCacheManager() method.
6. EntryProcessor
EntryProcessor allows us to modify Cache entries using atomic operations without having to re-add them to the Cache. To use it, we need to implement the EntryProcessor interface:
public class SimpleEntryProcessor implements EntryProcessor<String, String, String>, Serializable { public String process(MutableEntry<String, String> entry, Object... args) throws EntryProcessorException { if (entry.exists()) { String current = entry.getValue(); entry.setValue(current + " - modified"); return current; } return null; } }
Now, let’s use our EntryProcessor implementation:
@Test public void whenModifyValue_thenCorrect() { this.cache.invoke("key", new SimpleEntryProcessor()); assertEquals("value - modified", cache.get("key")); }
7. Event Listeners
Event Listeners allow us to take actions upon triggering any of the event types defined in the EventType enum, which are:
- CREATED
- UPDATED
- REMOVED
- EXPIRED
First, we need to implement interfaces of the events we’re going to use.
For example, if we want to use the CREATED and the UPDATED event types, then we should implement the interfaces CacheEntryCreatedListener and CacheEntryUpdatedListener.
Let’s see an example:
public class SimpleCacheEntryListener implements CacheEntryCreatedListener<String, String>, CacheEntryUpdatedListener<String, String>, Serializable { private boolean updated; private boolean created; // standard getters public void onUpdated( Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException { this.updated = true; } public void onCreated( Iterable<CacheEntryEvent<? extends String, ? extends String>> events) throws CacheEntryListenerException { this.created = true; } }
Now, let’s run our test:
@Test public void whenRunEvent_thenCorrect() throws InterruptedException { this.listenerConfiguration = new MutableCacheEntryListenerConfiguration<String, String>( FactoryBuilder.factoryOf(this.listener), null, false, true); this.cache.registerCacheEntryListener(this.listenerConfiguration); assertEquals(false, this.listener.getCreated()); this.cache.put("key", "value"); assertEquals(true, this.listener.getCreated()); assertEquals(false, this.listener.getUpdated()); this.cache.put("key", "newValue"); assertEquals(true, this.listener.getUpdated()); }
8. CacheLoader
CacheLoader allows us to use read-through mode to treat cache as the main data store and read data from it.
In a real-world scenario, we can have the cache read data from actual storage.
Let’s have a look at an example. First, we should implement the CacheLoader interface:
public class SimpleCacheLoader implements CacheLoader<Integer, String> { public String load(Integer key) throws CacheLoaderException { return "fromCache" + key; } public Map<Integer, String> loadAll(Iterable<? extends Integer> keys) throws CacheLoaderException { Map<Integer, String> data = new HashMap<>(); for (int key : keys) { data.put(key, load(key)); } return data; } }
And now, let’s use our CacheLoader implementation:
public class CacheLoaderTest { private Cache<Integer, String> cache; @Before public void setup() { CachingProvider cachingProvider = Caching.getCachingProvider(); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration<Integer, String> config = new MutableConfiguration<>() .setReadThrough(true) .setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>( new SimpleCacheLoader())); this.cache = cacheManager.createCache("SimpleCache", config); } @Test public void whenReadingFromStorage_thenCorrect() { for (int i = 1; i < 4; i++) { String value = cache.get(i); assertEquals("fromCache" + i, value); } } }
9. Conclusion
In this tutorial, we’ve seen what JCache is and explored some of its important features in a few practical scenarios.
As always, the full implementation of this tutorial can be found over on GitHub.