Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Spring has a caching abstraction that makes it very easy to add caching to your code without making a log of changes.

I will use this blog to provide an example that uses Spring Java configuration to demonstrate the configuration and usage of the basic cache methods.

Maven Dependencies

The following Maven dependencies are needed to enable the Spring Caching abstraction.


My entire pom.xml file is below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


            Needed for the EqualsBuilder and HashBuilder






Ehcache configuration

Next you will need an ehcache.xml file to configure your cache. An example file is located here.

I defined a cache named cars. It holds 1,000 entries that never expire. If the cache fills up, the first entries are Mine cache is configured as follows:

    <cache name="cars" maxEntriesLocalHeap="1000" eternal="true"/>

My entire ehcache.xml (which contains explanations for the various options) is below:

<ehcache xmlns:xsi="" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <!--<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd"-->
        DiskStore configuration

        The diskStore element is optional. To turn off disk store path creation, comment out the diskStore
        element below.

        Configure it if you have disk persistence enabled for any cache or if you use
        unclustered indexed search.

        If it is not configured, and a cache is created which requires a disk store, a warning will be
         issued and will automatically be used.

        diskStore has only one attribute - "path". It is the path to the directory where
        any required disk files will be created.

        If the path is one of the following Java System Property it is replaced by its value in the
        running VM. For backward compatibility these should be specified without being enclosed in the ${token}
        replacement syntax.

        The following properties are translated:
        * user.home - User's home directory
        * user.dir - User's current working directory
        * - Default temp file path
        * - A system property you would normally specify on the command line
          e.g. java ...

        Subdirectories can be specified below the property e.g.

    <diskStore path=""/>
        TransactionManagerLookup configuration
        This class is used by ehcache to lookup the JTA TransactionManager use in the application
        using an XA enabled ehcache. If no class is specified then DefaultTransactionManagerLookup
        will find the TransactionManager in the following order

         *GenericJNDI (i.e. jboss, where the property jndiName controls the name of the
                        TransactionManager object to look up)

        You can provide you own lookup class that implements the
        net.sf.ehcache.transaction.manager.TransactionManagerLookup interface.
    <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
        Specifies a CacheManagerEventListenerFactory which is notified when Caches are added
        or removed from the CacheManager.

        The attributes of CacheManagerEventListenerFactory are:
        * class - a fully qualified factory class name
        * properties - comma separated properties having meaning only to the factory.

        Sets the fully qualified class name to be registered as the CacheManager event listener.

        The events include:
        * adding a Cache
        * removing a Cache

        Callbacks to listener methods are synchronous and unsynchronized. It is the responsibility
        of the implementer to safely handle the potential performance and thread safety issues
        depending on what their listener is doing.

        If no class is specified, no listener is created. There is no default.
    <cacheManagerEventListenerFactory class="" properties=""/>
        (Enable for Terracotta clustered operation)

        Note: You need to install and run one or more Terracotta servers to use Terracotta clustering.

        Specifies a TerracottaConfig which will be used to configure the Terracotta
        runtime for this CacheManager.

        Configuration can be specified in two main ways: by reference to a source of
        configuration or by use of an embedded Terracotta configuration file.

        To specify a reference to a source (or sources) of configuration, use the url
        attribute.  The url attribute must contain a comma-separated list of:
        * path to Terracotta configuration file (usually named tc-config.xml)
        * URL to Terracotta configuration file
        * <server host>:<port> of running Terracotta Server instance

        Simplest example for pointing to a Terracotta server on this machine:
        <terracottaConfig url="localhost:9510"/>

        This element has two attributes "rejoin" and "wanEnabledTSA", which can take values of either "true" or "false":
        <terracottaConfig rejoin="true" wanEnabledTSA="true" url="localhost:9510" />

        By default, these attributes are false.

        Without rejoin, if the Terracotta Server is restarted the client cannot connect back to the
        server. When enabled, this allows the client to connect to the new cluster without the
        need to restart the node.

        When wanEnabledTSA is true, the client will wait for the WAN Orchestrator to provide the
        list of WAN enabled caches. Once the Orchestrator is up and running then the client will proceed
        to create the clustered data structures.

        Example using a path to Terracotta configuration file:
        <terracottaConfig url="/app/config/tc-config.xml"/>

        Example using a URL to a Terracotta configuration file:
        <terracottaConfig url="http://internal/ehcache/app/tc-config.xml"/>

        Example using multiple Terracotta server instance URLs (for fault tolerance):
        <terracottaConfig url="host1:9510,host2:9510,host3:9510"/>

        To embed a Terracotta configuration file within the ehcache configuration, simply
        place a normal Terracotta XML config within the <terracottaConfig> element.

                    <server host="server1" name="s1"/>
                    <server host="server2" name="s2"/>

        For more information on the Terracotta configuration, see the Terracotta documentation.
    <!--<terracottaConfig url="localhost:9510"/>-->
        Cache configuration

        The following attributes are required.

        Sets the name of the cache. This is used to identify the cache. It must be unique.

        Sets the maximum number of objects that will be created in memory.  0 = no limit.
        In practice no limit means Integer.MAX_SIZE (2147483647) unless the cache is distributed
        with a Terracotta server in which case it is limited by resources.

        Sets the maximum number of objects that will be maintained in the DiskStore
        The default value is zero, meaning unlimited.

        Sets whether elements are eternal. If eternal,  timeouts are ignored and the
        element is never expired.

        The following attributes and elements are optional.

        This feature is applicable only to Terracotta distributed caches.
        Sets the maximum number of entries that can be stored in the cluster. 0 = no limit.
        Note that clustered cache will still perform eviction if resource usage requires it.
        This property can be modified dynamically while the cache is operating.

        (boolean) This feature is available only in enterprise versions of Ehcache.
        When set to true, enables the cache to utilize off-heap memory
        storage to improve performance. Off-heap memory is not subject to Java
        GC. The default value is false.

        Defines how many bytes the cache may use from the VM's heap. If a CacheManager
        maxBytesLocalHeap has been defined, this Cache's specified amount will be
        subtracted from the CacheManager. Other caches will share the remainder.
        This attribute's values are given as <number>k|K|m|M|g|G for
        kilobytes (k|K), megabytes (m|M), or gigabytes (g|G).
        For example, maxBytesLocalHeap="2g" allots 2 gigabytes of heap memory.
        If you specify a maxBytesLocalHeap, you can't use the maxEntriesLocalHeap attribute.
        maxEntriesLocalHeap can't be used if a CacheManager maxBytesLocalHeap is set.

        Elements put into the cache will be measured in size using net.sf.ehcache.pool.sizeof.SizeOf
        If you wish to ignore some part of the object graph, see net.sf.ehcache.pool.sizeof.annotations.IgnoreSizeOf

        This feature is available only in enterprise versions of Ehcache.
        Sets the amount of off-heap memory this cache can use, and will reserve.

        This setting will set overflowToOffHeap to true. Set explicitly to false to disable overflow behavior.

        Note that it is recommended to set maxEntriesLocalHeap to at least 100 elements
        when using an off-heap store, otherwise performance will be seriously degraded,
        and a warning will be logged.

        The minimum amount that can be allocated is 128MB. There is no maximum.

        As for maxBytesLocalHeap, but specifies the limit of disk storage this cache will ever use.

        Sets the time to idle for an element before it expires.
        i.e. The maximum amount of time between accesses before an element expires
        Is only used if the element is not eternal.
        Optional attribute. A value of 0 means that an Element can idle for infinity.
        The default value is 0.

        Sets the time to live for an element before it expires.
        i.e. The maximum time between creation time and when an element expires.
        Is only used if the element is not eternal.
        Optional attribute. A value of 0 means that and Element can live for infinity.
        The default value is 0.

        The number of seconds between runs of the disk expiry thread. The default value
        is 120 seconds.

        This is the size to allocate the DiskStore for a spool buffer. Writes are made
        to this area and then asynchronously written to disk. The default size is 30MB.
        Each spool buffer is used only by its cache. If you get OutOfMemory errors consider
        lowering this value. To improve DiskStore performance consider increasing it. Trace level
        logging in the DiskStore will show if put back ups are occurring.

        whether the MemoryStore should be cleared when flush() is called on the cache.
        By default, this is true i.e. the MemoryStore is cleared.

        Policy would be enforced upon reaching the maxEntriesLocalHeap limit. Default
        policy is Least Recently Used (specified as LRU). Other policies available -
        First In First Out (specified as FIFO) and Less Frequently Used
        (specified as LFU)

        Whether an Element is copied when being read from a cache.
        By default this is false.

        Whether an Element is copied when being added to the cache.
        By default this is false.

        Cache persistence is configured through the persistence sub-element.  The attributes of the
        persistence element are:

        Configures the type of persistence provided by the configured cache.  This must be one of the
        following values:

        * localRestartable - Enables the RestartStore and copies all cache entries (on-heap and/or off-heap)
        to disk. This option provides fast restartability with fault tolerant cache persistence on disk.
        It is available for Enterprise Ehcache users only.

        * localTempSwap - Swaps cache entries (on-heap and/or off-heap) to disk when the cache is full.
        "localTempSwap" is not persistent.

        * none - Does not persist cache entries.

        * distributed - Defers to the <terracotta> configuration for persistence settings. This option
        is not applicable for standalone.

        When set to true write operations on the cache do not return until after the operations data has been
        successfully flushed to the disk storage.  This option is only valid when used with the "localRestartable"
        strategy, and defaults to false.

        The following example configuration shows a cache configured for localTempSwap restartability.

        <cache name="persistentCache" maxEntriesLocalHeap="1000">
            <persistence strategy="localTempSwap"/>

        Cache elements can also contain sub elements which take the same format of a factory class
        and properties. Defined sub-elements are:

        * cacheEventListenerFactory - Enables registration of listeners for cache events, such as
          put, remove, update, and expire.

        * bootstrapCacheLoaderFactory - Specifies a BootstrapCacheLoader, which is called by a
          cache on initialisation to prepopulate itself.

        * cacheExtensionFactory - Specifies a CacheExtension, a generic mechanism to tie a class
          which holds a reference to a cache to the cache lifecycle.

        * cacheExceptionHandlerFactory - Specifies a CacheExceptionHandler, which is called when
          cache exceptions occur.

        * cacheLoaderFactory - Specifies a CacheLoader, which can be used both asynchronously and
          synchronously to load objects into a cache. More than one cacheLoaderFactory element
          can be added, in which case the loaders form a chain which are executed in order. If a
          loader returns null, the next in chain is called.

        * copyStrategy - Specifies a fully qualified class which implements
 This strategy will be used for copyOnRead
          and copyOnWrite in place of the default which is serialization.

        Example of cache level resource tuning:
        <cache name="memBound" maxBytesLocalHeap="100m" maxBytesLocalOffHeap="4g" maxBytesLocalDisk="200g" />

        Cache Event Listeners

        All cacheEventListenerFactory elements can take an optional property listenFor that describes
        which events will be delivered in a clustered environment.  The listenFor attribute has the
        following allowed values:

        * all - the default is to deliver all local and remote events
        * local - deliver only events originating in the current node
        * remote - deliver only events originating in other nodes

        Example of setting up a logging listener for local cache events:

        <cacheEventListenerFactory class=""
            listenFor="local" />


        A <cache> can be made searchable by adding a <searchable/> sub-element. By default the keys
        and value objects of elements put into the cache will be attributes against which
        queries can be expressed.


        An "attribute" of the cache elements can also be defined to be searchable. In the example below
        an attribute with the name "age" will be available for use in queries. The value for the "age"
        attribute will be computed by calling the method "getAge()" on the value object of each element
        in the cache. See for the format of
        attribute expressions. Attribute values must also conform to the set of types documented in the interface

                <searchAttribute name="age" expression="value.getAge()"/>

        Attributes may also be defined using a JavaBean style. With the following attribute declaration
        a public method getAge() will be expected to be found on either the key or value for cache elements

                <searchAttribute name="age"/>

        In more complex situations you can create your own attribute extractor by implementing the
        AttributeExtractor interface. Providing your extractor class is shown in the following example:

                <searchAttribute name="age" class="com.example.MyAttributeExtractor"/>

        Use properties to pass state to your attribute extractor if needed. Your implementation must provide
        a public constructor that takes a single java.util.Properties instance

                <searchAttribute name="age" class="com.example.MyAttributeExtractor" properties="foo=1,bar=2"/>

        If you intend to use dynamic attribute extraction (see net.sf.ehcache.Cache.registerDynamicAttributesExtractor) then
        you need to enable it as follows:

            <searchable allowDynamicIndexing="true"/>

        Cache Exception Handling

        By default, most cache operations will propagate a runtime CacheException on failure. An
        interceptor, using a dynamic proxy, may be configured so that a CacheExceptionHandler can
        be configured to intercept Exceptions. Errors are not intercepted.

        It is configured as per the following example:

          <cacheExceptionHandlerFactory class="com.example.ExampleExceptionHandlerFactory"

        Caches with ExceptionHandling configured are not of type Cache, but are of type Ehcache only,
        and are not available using CacheManager.getCache(), but using CacheManager.getEhcache().

        Cache Loader

        A default CacheLoader may be set which loads objects into the cache through asynchronous and
        synchronous methods on Cache. This is different to the bootstrap cache loader, which is used
        only in distributed caching.

        It is configured as per the following example:

            <cacheLoaderFactory class="com.example.ExampleCacheLoaderFactory"

        Element value comparator

        These two cache atomic methods:
          removeElement(Element e)
          replace(Element old, Element element)

        rely on comparison of cached elements value. The default implementation relies on Object.equals()
        but that can be changed in case you want to use a different way to compute equality of two elements.

        This is configured as per the following example:

        <elementValueComparator class=""/>

        The MyElementComparator class must implement the is
        interface. The default implementation is

        SizeOf Policy

        Control how deep the SizeOf engine can go when sizing on-heap elements.

        This is configured as per the following example:

        <sizeOfPolicy maxDepth="100" maxDepthExceededBehavior="abort"/>

        maxDepth controls how many linked objects can be visited before the SizeOf engine takes any action.
        maxDepthExceededBehavior specifies what happens when the max depth is exceeded while sizing an object graph.
         "continue" makes the SizeOf engine log a warning and continue the sizing. This is the default.
         "abort"    makes the SizeOf engine abort the sizing, log a warning and mark the cache as not correctly tracking
                    memory usage. This makes Ehcache.hasAbortedSizeOf() return true when this happens.

        The SizeOf policy can be configured at the cache manager level (directly under <ehcache>) and at
        the cache level (under <cache> or <defaultCache>). The cache policy always overrides the cache manager
        one if both are set. This element has no effect on distributed caches.


        To enable an ehcache as transactions, set the transactionalMode

        transactionalMode="xa" - high performance JTA/XA implementation
        transactionalMode="xa_strict" - canonically correct JTA/XA implementation
        transactionMode="local" - high performance local transactions involving caches only
        transactionalMode="off" - the default, no transactions

        If set, all cache operations will need to be done through transactions.

        To prevent users keeping references on stored elements and modifying them outside of any transaction's control,
        transactions also require the cache to be configured copyOnRead and copyOnWrite.


        A CacheWriter can be set to write to an underlying resource. Only one CacheWriter can be
        configured per cache.

        The following is an example of how to configure CacheWriter for write-through:

            <cacheWriter writeMode="write-through" notifyListenersOnException="true">
                <cacheWriterFactory class="net.sf.ehcache.writer.TestCacheWriterFactory"

        The following is an example of how to configure CacheWriter for write-behind:

            <cacheWriter writeMode="write-behind" minWriteDelay="1" maxWriteDelay="5"
                         rateLimitPerSecond="5" writeCoalescing="true" writeBatching="true" writeBatchSize="1"
                         retryAttempts="2" retryAttemptDelaySeconds="1">
                <cacheWriterFactory class="net.sf.ehcache.writer.TestCacheWriterFactory"

        The cacheWriter element has the following attributes:
        * writeMode: the write mode, write-through or write-behind

        These attributes only apply to write-through mode:
        * notifyListenersOnException: Sets whether to notify listeners when an exception occurs on a writer operation.

        These attributes only apply to write-behind mode:
        * minWriteDelay: Set the minimum number of seconds to wait before writing behind. If set to a value greater than 0,
          it permits operations to build up in the queue. This is different from the maximum write delay in that by waiting
          a minimum amount of time, work is always being built up. If the minimum write delay is set to zero and the
          CacheWriter performs its work very quickly, the overhead of processing the write behind queue items becomes very
          noticeable in a cluster since all the operations might be done for individual items instead of for a collection
          of them.
        * maxWriteDelay: Set the maximum number of seconds to wait before writing behind. If set to a value greater than 0,
          it permits operations to build up in the queue to enable effective coalescing and batching optimisations.
        * writeBatching: Sets whether to batch write operations. If set to true, writeAll and deleteAll will be called on
          the CacheWriter rather than write and delete being called for each key. Resources such as databases can perform
          more efficiently if updates are batched, thus reducing load.
        * writeBatchSize: Sets the number of operations to include in each batch when writeBatching is enabled. If there are
          less entries in the write-behind queue than the batch size, the queue length size is used.
        * rateLimitPerSecond: Sets the maximum number of write operations to allow per second when writeBatching is enabled.
        * writeCoalescing: Sets whether to use write coalescing. If set to true and multiple operations on the same key are
          present in the write-behind queue, only the latest write is done, as the others are redundant.
        * retryAttempts: Sets the number of times the operation is retried in the CacheWriter, this happens after the
          original operation.
        * retryAttemptDelaySeconds: Sets the number of seconds to wait before retrying an failed operation.


        Use this element when data should remain in the cache regardless of resource constraints.
        Unexpired entries can never be flushed to a lower tier or be evicted.

        This element has a required attribute (store) to specify which data tiers the cache should be pinned to:
        * localMemory: Cache data is pinned to the local heap (or off-heap for BigMemory Go and BigMemory Max).
        * inCache: Cache data is pinned in the cache, which can be in any tier cache data is stored.

            <pinning store="inCache"/>

        Cache Extension

        CacheExtensions are a general purpose mechanism to allow generic extensions to a Cache.
        CacheExtensions are tied into the Cache lifecycle.

        CacheExtensions are created using the CacheExtensionFactory which has a
        <code>createCacheCacheExtension()</code> method which takes as a parameter a
        Cache and properties. It can thus call back into any public method on Cache, including, of
        course, the load methods.

        Extensions are added as per the following example:

             <cacheExtensionFactory class="com.example.FileWatchingCacheRefresherExtensionFactory"
                                 properties="refreshIntervalMillis=18000, loaderTimeout=3000,
                                             flushPeriod=whatever, someOtherProperty=someValue ..."/>

        Cache Decorator Factory

        Cache decorators can be configured directly in ehcache.xml. The decorators will be created and added to the CacheManager.
        It accepts the name of a concrete class that extends net.sf.ehcache.constructs.CacheDecoratorFactory
        The properties will be parsed according to the delimiter (default is comma ',') and passed to the concrete factory's
        <code>createDecoratedEhcache(Ehcache cache, Properties properties)</code> method along with the reference to the owning cache.

        It is configured as per the following example:

          properties="property1=true ..." />

        Distributed Caching with Terracotta

        Distributed Caches connect to a Terracotta Server Array. They are configured with the <terracotta> sub-element.

        The <terracotta> sub-element has the following attributes:

        * clustered=true|false - indicates whether this cache should be clustered (distributed) with Terracotta. By
          default, if the <terracotta> element is included, clustered=true.

        * copyOnRead=true|false - indicates whether cache values are deserialized on every read or if the
          materialized cache value can be re-used between get() calls. This setting is useful if a cache
          is being shared by callers with disparate classloaders or to prevent local drift if keys/values
          are mutated locally without being put back in the cache.

          The default is false.

        * consistency=strong|eventual - Indicates whether this cache should have strong consistency or eventual
          consistency. The default is eventual. See the documentation for the meaning of these terms.

        * synchronousWrites=true|false

          Synchronous writes (synchronousWrites="true")  maximize data safety by blocking the client thread until
          the write has been written to the Terracotta Server Array.

          This option is only available with consistency=strong. The default is false.

        * concurrency - the number of segments that will be used by the map underneath the Terracotta Store.
          Its optional and has default value of 0, which means will use default values based on the internal
          Map being used underneath the store.

          This value cannot be changed programmatically once a cache is initialized.

        The <terracotta> sub-element also has a <nonstop> sub-element to allow configuration of cache behaviour if a distributed
        cache operation cannot be completed within a set time or in the event of a clusterOffline message. If this element does not appear, nonstop behavior is off.

        <nonstop> has the following attributes:

        *  enabled="true" - defaults to true.

        *  timeoutMillis - An SLA setting, so that if a cache operation takes longer than the allowed ms, it will timeout.

        *  searchTimeoutMillis - If a cache search operation in the nonstop mode takes longer than the allowed ms, it will timeout.

        *  immediateTimeout="true|false" - What to do on receipt of a ClusterOffline event indicating that communications
           with the Terracotta Server Array were interrupted.

        <nonstop> has one sub-element, <timeoutBehavior> which has the following attribute:

        *  type="noop|exception|localReads|localReadsAndExceptionOnWrite" - What to do when a timeout has occurred. Exception is the default.

        Simplest example to indicate clustering:

        To indicate the cache should not be clustered (or remove the <terracotta> element altogether):
            <terracotta clustered="false"/>

        To indicate the cache should be clustered using "eventual" consistency mode for better performance :
            <terracotta clustered="true" consistency="eventual"/>

        To indicate the cache should be clustered using synchronous-write locking level:
            <terracotta clustered="true" synchronousWrites="true"/>
        Default Cache configuration. These settings will be applied to caches
        created programmatically using CacheManager.add(String cacheName).
        This element is optional, and using CacheManager.add(String cacheName) when
        its not present will throw CacheException

        The defaultCache has an implicit name "default" which is a reserved cache name.
    <defaultCache maxEntriesLocalHeap="0" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200">

    <cache name="cars" maxEntriesLocalHeap="1000" eternal="true"/>

        Sample caches. Following are some example caches. Remove these before use.
        Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever is
        defined on your system. On a standard Linux system this will be /tmp"
    <cache name="sampleCache1"
        <persistence strategy="localTempSwap"/>
        Sample cache named sampleCache2
        This cache has a maximum of 1000 elements in memory. There is no overflow to disk, so 1000
        is also the maximum cache size. Note that when a cache is eternal, timeToLive and
        timeToIdle are not used and do not need to be specified.
    <cache name="sampleCache2" maxEntriesLocalHeap="1000" eternal="true" memoryStoreEvictionPolicy="FIFO"/>
        Sample cache named sampleCache3. This cache overflows to disk. The disk store is
        persistent between cache and VM restarts. The disk expiry thread interval is set to 10
        minutes, overriding the default of 2 minutes.
    <cache name="sampleCache3"
        Sample Terracotta clustered cache named sampleTerracottaCache.
        This cache uses Terracotta to cluster the contents of the cache.
    <cache name="sampleTerracottaCache"
          Sample xa enabled cache named xaCache
        <cache name="xaCache"
          Sample copy on both read and write cache named copyCache
          using the default (explicitly configured here as an example) ReadWriteSerializationCopyStrategy
          class could be any implementation of
        <cache name="copyCache"
            <copyStrategy class="" />
          Sample, for Enterprise Ehcache only, demonstrating a tiered cache with in-memory, off-heap and disk stores. In this example the in-memory (on-heap) store is limited to 10,000 items ... which for example for 1k items would use 10MB of memory, the off-heap store is limited to 4GB and the disk store is unlimited in size.
        <cache name="tieredCache"
            <persistence strategy="localTempSwap"/>
          Sample, for Enterprise Ehcache only, demonstrating a restartable cache with in-memory and off-heap stores.
        <cache name="restartableCache"
             <persistence strategy="localRestartable"/>

Spring Configuration

There are three things that are needed to enable the Spring caching abstraction when using Spring Java configuration.

  • @EnableCaching – Enables Spring’s annotation-driven cache management capability, similar to the support found in Spring’s XML namespace.
  • CacheManager – Spring’s central cache manager SPI
  • EhCacheManagerFactoryBean – FactoryBean that exposes an EhCache CacheManager instance

Below is the code:

package com.javaninja.spring.ehcache;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

 * @author norris.shelton
public class SpringContext {

     * Creates a Spring cache manager.
     * @return spring cache manager
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManagerFactoryBean().getObject());

     * Create the Ehcache manager factory bean.  Set the bean shared property to shared so other users in this
     * classloader can access it.
     * @return Shared Ehcache manager factory bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() {
        EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        return ehCacheManagerFactoryBean;

Service Code

Below is the service class that I added the caching to. Note the @Cacheable annotation. The simplest @Cacheable call takes the name of the cache to use for the method. The method parameters will form the basis for the cache key and the return object will be the cache value.. I added some logging so that we can use the log to verify that the method was not accessed because there was a cache hit.

package com.javaninja.spring.ehcache;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

 * @author norris.shelton
public class CarService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private List<Car> cars = new LinkedList<>();

     * Creates a new car.
     * @return Car object with values populated.
    public Car createCar() {
        Car car = new Car();
        car.setMake("Make-" + RandomStringUtils.randomAlphabetic(10));
        car.setModel("Model-" + RandomStringUtils.randomAlphabetic(10));
        car.setVin("Vin-" + RandomStringUtils.randomAlphanumeric(30));

        // Add to my list of all cars
        cars.add(car);"added car to list {}", car);

        return car;

    @Cacheable(value = "cars")
    public Car getCar(String vin) {"inside ");
        Car car = null;
        for (Car car1 : cars) {
  "iterating over car");
            if (car1.getVin().equals(vin)) {
                car = car1;
      "found car {}", car1);
        return car;

Maven Test Dependencies

I added the following dependencies to enable the proper test support.


Junit test

I created a Junit test class. It pre-loads all of the cars into the service’s car list. The test calls the method twice. The first time the cache is empty and every item has to be iterated. The second time, the cache is fully warm and there is no iteration.

package com.javaninja.spring.ehcache;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

 * @author norris.shelton
@ContextConfiguration(classes = SpringContext.class)
public class TestCarService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private CarService carService;

    private String vin;

     * Creates cars to look for.
    public void before() {
        Car car;
        for (int i = 0; i < 10; i++) {
            car = carService.createCar();

            // store the value of the last car
            vin = car.getVin();

     * Tests the get car method.
     * @throws Exception
    public void testGetCar() throws Exception {
        // the first time the get cars method is called, the cache is empty"beginning of first run");
        Car car = carService.getCar(vin);  // find the last car added
        assertEquals(vin, car.getVin());"end of first run");

        // the second time the get cars method is called, the cache is fully populated"beginning of second run");
        car = carService.getCar(vin);  // find the last car added
        assertEquals(vin, car.getVin());"end of first run");

Below is the log for the test run. You can clearly see that during the first run, the list of cars has to be iterated over. During the next run, the method is not entered at all. The method call results in a cache hit.

10:07:53.156 [main] INFO  c.j.spring.ehcache.TestCarService - beginning of first run
10:07:53.160 [main] INFO  c.j.spring.ehcache.CarService - inside 
10:07:53.160 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.160 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.160 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.160 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - iterating over car
10:07:53.161 [main] INFO  c.j.spring.ehcache.CarService - found car com.javaninja.spring.ehcache.Car@5456afaa[make=Make-WmlGJCSagi,model=Model-dYdOzzPNHi,vin=Vin-zfXislLcOjxlPWMNBHy6RnmvS5xAWy]
10:07:53.163 [main] INFO  c.j.spring.ehcache.TestCarService - end of first run
10:07:53.163 [main] INFO  c.j.spring.ehcache.TestCarService - beginning of second run
10:07:53.163 [main] INFO  c.j.spring.ehcache.TestCarService - end of first run


You now have the information needed to enable the base Spring cache abstraction using Ehcache as the implementation.

The example project for this blog entry is located on GitHub at sheltonn / spring-ehcache

February 29th, 2016

Posted In: Ehcache, Java, java ninja, Javaninja, Spring

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :