[Logo] Terracotta Discussion Forums (LEGACY READ-ONLY ARCHIVE)
  [Search] Search   [Recent Topics] Recent Topics   [Members]  Member Listing   [Groups] Back to home page 
[Register] Register / 
[Login] Login 
[Expert]
How to check whether object is removed after 'timeToLiveSeconds'.  XML
Forum Index -> General
Author Message
Niteesh

neo

Joined: 10/09/2012 22:03:57
Messages: 8
Location: Bangalore, India
Offline

Hi All,
I am using ehCache level2 for hibernate. I want to know how can i check whether cached object is removed after TTL. I have connected it to dev-console too. But there, cached object count is not at all decreasing. And once its started there are some extra cached objects(For ex:Caching:688,offheap:0,tatal:957). I am adding only 2 objects.
Here is my code:

//import net.sf.ehcache.Cache;

import net.sf.ehcache.CacheManager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.stat.SecondLevelCacheStatistics;

public class HibernateEhCacheExample {
public static void main(String[] args) {

Session session1 = null;

CacheManager manager = new CacheManager("src/ehcache.xml");//Loading existing cache manager


SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();//Read hibernate.cfg.xml and prepare hibernate for use
//Opening first session
session1 =sessionFactory.openSession();
System.out.println("Cache Statistics when its empty");
System.out.println("Cache Hits----"+sessionFactory.getStatistics().getSecondLevelCacheHitCount() );
System.out.println("Cache Misses----"+sessionFactory.getStatistics().getSecondLevelCacheMissCount());

Object o = session1.load(Contact.class, new Integer(6));// Loading the first object
Contact c = (Contact) o;

System.out.println("Cache Mode"+session1.getCacheMode());// NORMAL, IGNORE, GET, PUT.. etc
System.out.println("Loaded First Contact object's Name is___"+c.getFirstName());
System.out.println("Object Loaded from DB successfully.....!!");


session1.close();//Closing first session

System.out.println("------------------------------");
System.out.println("Waiting for exceeding Cache TimeToLive ......");
//Waiting for Cache timeout i.e 5000ms

try {
Thread.sleep(5000); //Waiting for Cache timeout i.e 5000ms
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("5 seconds compelted......!!!!!!!!");

// Create second session after timeout
Session session2 = sessionFactory.openSession();
Object o2 = session2.load(Contact.class, new Integer(6));// Loading the same first object from DB
Contact c2 = (Contact) o2;
System.out.println("");
System.out.println("Loaded First Contact object's Name is___"+c2.getFirstName());
System.out.println("Object loaded from the database, since timeout happened...!!");
//System.out.println("Cache Hits----"+sessionFactory.getStatistics().getSecondLevelCacheHitCount() );
System.out.println("Cache Misses----"+sessionFactory.getStatistics().getSecondLevelCacheMissCount());
System.out.println("Cache Hits----"+sessionFactory.getStatistics().getSecondLevelCacheHitCount() );

// Load a different object 7 in same session
Object o4 = session2.load(Contact.class, new Integer(7));
Contact c4 = (Contact) o4;
System.out.println("Loaded Second Contact object's Name is___"+c4.getFirstName());
System.out.println("Second Object loaded from DB since its a new Object.....!!");
System.out.println("Cache Hits----"+sessionFactory.getStatistics().getSecondLevelCacheHitCount() );
System.out.println("Cache Misses----"+sessionFactory.getStatistics().getSecondLevelCacheMissCount());

session2.close();

//Creating second session before cache timeout
Session session3 = sessionFactory.openSession();
Object o3 = session3.load(Contact.class, new Integer(7));
Contact c3 = (Contact) o3;
System.out.println("Loaded Second Contact object's Name is____"+c3.getFirstName());
System.out.println("Second Object loaded from global cache successfully.....!!");

SecondLevelCacheStatistics slcs = session3.getSessionFactory().getStatistics().getSecondLevelCacheStatistics("roseindia.tutorial.hibernate.Contact");

System.out.println("Cache Hits----"+sessionFactory.getStatistics().getSecondLevelCacheHitCount() );
System.out.println("Cache Misses----"+sessionFactory.getStatistics().getSecondLevelCacheMissCount());

System.out.println("----------------------Summary--------------------------------------");
System.out.println("Element Count in Cache Memory--"+slcs.getElementCountInMemory());
System.out.println("Put Count in Cache--"+slcs.getPutCount());
System.out.println("Element Count in Disk--"+slcs.getElementCountOnDisk());

// For Checking whether Key Exists or Not
/* for(Iterator<Object> iterator = keyList.iterator(); iterator.hasNext();){
Object key = iterator.next();
if(manager.getCache("roseindia.tutorial.hibernate.Contact").isKeyInCache(key)){

System.out.println("Key Object exists--"+key);
}
} */

/* Boolean status=true;

while(status)
{

} */

session3.close();



sessionFactory.close();


}
}
[/code]

ehCache.xml:
<cache name="Contact" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="5" memoryStoreEvictionPolicy="LFU" diskPersistent="false">
<terracotta/>
</cache>

I am also getting the below errors after 5sec for runs (except first one after i start tc server).

Exception in thread "main" org.hibernate.cache.CacheException: net.sf.ehcache.CacheException: Uncaught exception in get() - org.hibernate.cache.CacheKey.<init>(Ljava/io/Serializable;Lorg/hibernate/type/Type;Ljava/lang/String;Lorg/hibernate/EntityMode;Lorg/hibernate/engine/SessionFactoryImplementor;)V
at org.hibernate.cache.EhCache.get(EhCache.java:123)
at org.hibernate.cache.NonstrictReadWriteCache.get(NonstrictReadWriteCache.java:41)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromSecondLevelCache(DefaultLoadEventListener.java:469)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:350)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:166)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:140)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:119)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:571)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:59)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:80)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:133)
at roseindia.tutorial.hibernate.Contact$$EnhancerByCGLIB$$8bff1cfa.getFirstName(<generated>)
at roseindia.tutorial.hibernate.HibernateEhCacheExample.main(HibernateEhCacheExample.java:30)
Caused by: net.sf.ehcache.CacheException: Uncaught exception in get() - org.hibernate.cache.CacheKey.<init>(Ljava/io/Serializable;Lorg/hibernate/type/Type;Ljava/lang/String;Lorg/hibernate/EntityMode;Lorg/hibernate/engine/SessionFactoryImplementor;)V
at org.terracotta.modules.ehcache.store.ClusteredSafeStore.get(ClusteredSafeStore.java:685)
at net.sf.ehcache.Cache.searchInStoreWithStats(Cache.java:1960)
at net.sf.ehcache.Cache.get(Cache.java:1588)
at net.sf.ehcache.Cache.get(Cache.java:1561)
at org.hibernate.cache.EhCache.get(EhCache.java:110)
... 12 more
Caused by: java.lang.NoSuchMethodError: org.hibernate.cache.CacheKey.<init>(Ljava/io/Serializable;Lorg/hibernate/type/Type;Ljava/lang/String;Lorg/hibernate/EntityMode;Lorg/hibernate/engine/SessionFactoryImplementor;)V
at org.terracotta.modules.ehcache.store.HibernateElementSerializationStrategy.readStringKey(HibernateElementSerializationStrategy.java:49)
at org.terracotta.cache.serialization.DsoSerializationStrategy2.deserializeStringKey(DsoSerializationStrategy2.java:74)
at org.terracotta.modules.ehcache.store.ValueModeHandlerSerialization.realKeyObjectFor(ValueModeHandlerSerialization.java:139)
at org.terracotta.modules.ehcache.store.ValueModeHandlerSerialization.getRealKeyObject(ValueModeHandlerSerialization.java:126)
at org.terracotta.modules.ehcache.store.ValueModeHandlerHibernate.getRealKeyObject(ValueModeHandlerHibernate.java:8)
at org.terracotta.modules.ehcache.store.ClusteredStoreBackendImpl$TDCWithEvents.onExpiry(ClusteredStoreBackendImpl.java:250)
at org.terracotta.cache.TerracottaDistributedCache.expire(TerracottaDistributedCache.java:518)
at org.terracotta.cache.TerracottaDistributedCache.getNonExpiredEntry(TerracottaDistributedCache.java:257)
at org.terracotta.cache.TerracottaDistributedCache.getNonExpiredEntryUnlocked(TerracottaDistributedCache.java:157)
at org.terracotta.cache.TerracottaDistributedCache.unlockedGetTimestampedValue(TerracottaDistributedCache.java:654)
at org.terracotta.modules.ehcache.store.ClusteredStoreBackendImpl.unlockedGetTimestampedValue(ClusteredStoreBackendImpl.java:183)
at org.terracotta.modules.ehcache.store.backend.NonStrictBackend.get(NonStrictBackend.java:181)
at org.terracotta.modules.ehcache.store.ClusteredStore.doGet(ClusteredStore.java:419)
at org.terracotta.modules.ehcache.store.ClusteredStore.get(ClusteredStore.java:405)
at org.terracotta.modules.ehcache.store.ClusteredSafeStore.get(ClusteredSafeStore.java:682)
... 16 more
[Yahoo!]
klalithr

consul

Joined: 01/23/2011 10:58:07
Messages: 489
Offline

A couple of things

a) TTI/TTL eviction is inline. What that means is that the next time the element is accessed, thats when its evicted. So if you have the TTL as 5 minutes and look at the dev console after 5 minutes, there will not be a thread that evicts these values. However, when you access the element anytime after 5 min, you will still see the count reduced (and the element evicted)
b)The underlying issue is
java.lang.NoSuchMethodError: org.hibernate.cache.CacheKey
This is usually caused due to classpath issues. Check the version of the ehcache and hibernate jars to make sure they are the latest.

Karthik Lalithraj (Terracotta)
alexsnaps

consul

Joined: 06/19/2009 09:06:00
Messages: 484
Offline

Can you indicate what version of ehcache you are using, as well as the Hibernate version. Also seeing your mappings and Hibernate config would help here...

Alex Snaps (Terracotta engineer)
Niteesh

neo

Joined: 10/09/2012 22:03:57
Messages: 8
Location: Bangalore, India
Offline

Thanks Karthik for quick reply. Ya, I will check the versions of them.
But what I am confused is, if the object is evicted from cache after the timeout, my code should load the value from DB as before right? Why it is throwing errors? And also this behaviour is not consistent. When i start my tc-server first time and run this code it sometimes runs without errors. But when i run second time without restarting tc server, its giving errors each time.

Need your advice.
Thanks,
Niteesh
[Yahoo!]
Niteesh

neo

Joined: 10/09/2012 22:03:57
Messages: 8
Location: Bangalore, India
Offline

Thanks Alex for the reply.

My jar details are below:
hibernate3.jar
ehcache-core-ee-2.6.0.jar
ehcache-terracotta-ee-2.6.0.jar
terracotta-toolkit-1.6-runtime-ee-5.0.0.jar

hibernate-config.xml:
----------------------------------------------------------------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@blramd4.eur.ad.sag:1521:R11U2DB1</property>
<property name="hibernate.connection.username">asar2</property>
<property name="hibernate.connection.password">asar2</property>
<property name="hibernate.connection.pool_size">20</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<!-- <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>-->
<property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.default_batch_fetch_size">16</property>
<property name="hibernate.jdbc.batch_size">50</property>

<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>

</session-factory>
</hibernate-configuration>
----------------------------------------------------------------------------------
contact.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<cache usage="nonstrict-read-write" />
<id name="id" type="int" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
----------------------------------------------------------------------------------

Awaiting your response,

Regards,
Niteesh:)
[Yahoo!]
alexsnaps

consul

Joined: 06/19/2009 09:06:00
Messages: 484
Offline

You shouldn't use both:
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>

Given your versions you should use the latter only. Can you check whether this helps ?

Alex Snaps (Terracotta engineer)
Niteesh

neo

Joined: 10/09/2012 22:03:57
Messages: 8
Location: Bangalore, India
Offline

Hi Alex,

I have tried removing the <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> . But no change in behaviour.

The point to consider here is, I am getting the errors only in case of giving Thread.sleep(5000); duration. If i restart my tc server and give low value like 2000ms or so, that will run successfully.

Can somebody explain this behaviour? If at all my object is evicted after TTL, it should be loaded from DB rite? Why its throwing error?

Regards,
Niteesh
[Yahoo!]
 
Forum Index -> General
Go to:   
Powered by JForum 2.1.7 © JForum Team