Spring – Another unnamed CacheManager already exists in the same VM (ehCache 2.5)

ehcachejunitspring

This is what happens when I run my junit tests…

Another CacheManager with same name 'cacheManager' already exists in the same VM. Please 
provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same
   CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.

The source of the existing CacheManager is: 
 DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]

What's the reason behind the exception. Could there be more than 1 cacheManager running simultaneously?

This is how I configured the cachManager using Sping 3.1.1. It sets explicitly the scope of the cacheManager to "singleton"

<ehcache:annotation-driven />

<bean
    id="cacheManager"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
    scope="singleton"
    />

The ehcache.xml looks like

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
     updateCheck="false"
     maxBytesLocalHeap="100M" 
     name="cacheManager"
     >
 ....
 </ehcache>

Finally my class

@Component
public class BookingCache implements CacheWrapper<String, BookingUIBean> {

     @Autowired
     private CacheManager ehCacheManager;
      ....
}

I'm very sure that I'm dealing with only one cacheManager in my code base. Something else is probably running the n-th instance.

Best Answer

Your EhCacheManagerFactoryBean may be a singleton, but it's building multiple CacheManagers and trying to give them the same name. That violates Ehcache 2.5 semantics.

Versions of Ehcache before version 2.5 allowed any number of CacheManagers with the same name (same configuration resource) to exist in a JVM.

Ehcache 2.5 and higher does not allow multiple CacheManagers with the same name to exist in the same JVM. CacheManager() constructors creating non-Singleton CacheManagers can violate this rule

Tell the factory bean to created a shared instance of the CacheManager in the JVM by setting the shared property to true.

<bean id="cacheManager"
      class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
      p:shared="true"/>
Related Topic