Caching Method Results With JCache

DZone 's Guide to

Caching Method Results With JCache

Take a look at how to make use of JCache, a simple annotation, and a few associated dependencies to store method results.

· Java Zone ·
Free Resource

In JCache, there is a handy functionality that transparently caches the result of methods. You can annotate methods of managed beans with @CacheResult, and the result of the first call will be returned again without calling the actual method a second time.

import javax.cache.annotation.CacheResult;
// ...

public class Calculator {

    public String calculate() {
        // do some heavy lifting...

        return "Hi Duke, it's " + Instant.now();

If the bean is injected and the method calculate is called, the result will be cached after the first call. By default, this mechanism doesn’t cache and return exceptions.

We can include the calculator in a JAX-RS resource as follows:

public class CalculationResource {

    Calculator calculator;

    public String calculation() {
        return calculator.calculate();

Calling that HTTP resource will return the same value for all subsequent invocations.

For this example to run on Java EE application servers we, for now, have to declare the interceptor that is responsible for caching the result. This is due to JCache not being included in the EE umbrella. Therefore, this small configuration overhead needs to be done for now.

If you want to run this example in WildFly specify the interceptor in the beans.xml:


WildFly uses Infinispan, which needs to be added in the pom.xml.


This post was reposted from my newsletter issue 011.

caching, java, java ee, jcache, tutorial

Published at DZone with permission of Sebastian Daschner , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}