6

Though I guess its highly unlikely - but is there any way to clear the ehcache without restarting the server? I need to clear the cache for some testing - I cannot change the code and cannot afford to restart server at multiple times.

PS: I am using apache-tomcat-5.5.25 Please let me know. Thanks, psvm

Vishal
  • 2,711
  • 7
  • 33
  • 42
  • this is a server question, so, serverfault.com suits you. – Raptor Jun 06 '12 at 10:05
  • Why can't you restart the server? This sounds like you're testing on live hardware or on a very restricted set of rigs, which breaks your test isolation and could invalidate your testing. Unless your deployment is enormously byzantine, I'd suggest having isolated rigs, Tomcat isn't exactly a resource hog out of the box. – Jeff Watkins Jun 06 '12 at 10:07

2 Answers2

8

Do you expose Ehcache via JMX? Then you could clear the cache using JMX operations by using a tool like e.g. jvisualvm. Look for MBeans like net.sf.ehcache.CacheManager which provide a clearAll() operation.

jeha
  • 10,562
  • 5
  • 50
  • 69
0

Using spring+hibernate and exposing mbean:

import org.hibernate.Cache;
import org.hibernate.SessionFactory;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("CacheManagerMBean")
public class CacheManagerMBean {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CacheManagerMBean.class);

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public void clearCache() {
        Cache cache = sessionFactory.getCache();
        if (null != cache) {
            logger.info("Clearing cache...");
            cache.evictAll();
            cache.evictAllRegions();
            logger.info("Clearing cache...Done!");
        } else {
            logger.error("No second level cache available for session-factory");
        }
    }

}

XML Config:

<bean id="jmxExporterCacheManagerMBean" class="org.springframework.jmx.export.MBeanExporter">
        <property name="beans">
            <map>
                <entry key="CacheManager:type=SecondLevelCacheManager">
                    <ref bean="CacheManagerMBean"/>
                </entry>
            </map>
        </property>
    </bean>

And then connect to the java process using jconsole and use Mbean method invocation - to clear the second level cache!

Nisarg Panchal
  • 131
  • 1
  • 6