Ehcache for Hibernate and within Application

2011-09-20
2013-05-14
  • Rob Connell
    Rob Connell
    2011-09-20

    We are using EhCache both for Hibernate and within our applications and we  were having some issues relating to multipleCacheManager threads as some of the code was using new CacheManager () rather than say CacheManager.getInstance (which if used everywhere only uses the one CacheManager instance which sounds prefereable).

    In order to resolve this I changed all the new CacheManager() code to CacheManager.getInstance which resolved the cachemanager thread issue but it caused a Cache is not alive error to be thrown by net.sf.ehcache.Cache in the checkStatus method.

    After some debugging it appears that org.hibernate.impl.SessionFactoryImpl is calling the stop method in the class referenced by the hibernate.cache.provider_class implementation on startup of the application server (which is weird in itself). The default implementation for this class is org.hibernate.cache.EhCacheProvider which within the stop method destoys the CacheManager instance (presumably on the basis that Hibernate is the only product using the CacheManager). This in turn is removing the CacheManager instance that is pointing to all of the application Caches outside of Hibernate.

    This issue seems to be referenced in a couple of posts but I am looking for the best practice approach to get around this issue.

    The way that I have got around this so far is tailoring the EhCacheProvider code so that it does not remove the CacheManager singleton in the stop method but I am concerned about what other implications this may have.

    As stated I already have a solution so I really only need confirmation that this is a suitable solution or another Best Practice way of getting around this issue.