Introduction

JbossCache is a wonderfully complex piece of software. Trying to use it with Hibernate might seem an easy task at first but in reality it can also prove wonderfully complicated.

First question is: why would you consider using it in the first place? Compared to ehcache for instance there are a few theoretical advantages: clustering (scalability), configurability and jmx monitoring.

Next question which is not quite obvious is which version to use? The answer is a bit complicated since there are a lot of changes in versions which vary from architectural to configuration points. This document is concerned with integration of hibernate 3.3.1 with jboss cache 3.1.0 (Cascabel) as they are shipped in jboss 5.1.0.GA.

Choices

I think most people consider that cache integration should be a matter of switching a config option. I cannot argue with this logic and for them the most appropriate configuration (as described in most documents) is as following (if using a hibernate-service.xml .har configuration):

<pre lang="xml"><property name="cacheRegionFactoryClass">org.hibernate.cache.jbc2.MultiplexedJBossCacheRegionFactory</property>

along with activation of second level and query cache:

<pre lang="xml"><property name="queryCacheEnabled">true</property>
<property name="secondLevelCacheEnabled">true</property>

This will probably work from start but also from start you will loose one of the advantages: jmx monitoring

Let’s go back to the cacheRegionFactoryClass and it’s hibernate.cache.region.factory_class equivalent. The hibernate documentation states there are 4 options for this property. Here is my understanding of them:

  • SharedJBossCacheRegionFactory will create a Cache (as in org.jboss.cache.Cache) based on a treecache.xml configuration and use it for it’s caching purposes. You can provide your configuration (in fact you must provide it) and everything seems perfect except that you cannot have jmx instrumentation. I have found no way to obtain the Cache from a SessionFactory and pass it to a CacheJmxWrapper for instrumentation.
  • JndiSharedJBossCacheRegionFactory seems the perfect solution for the above problem as you can create your cache and jmx via a -jboss-beans.xml configuration and then pass it to hibernate. Can you? No. As there is no way to bind the cache to JNDI from the -jboss-beans.xml configuration. No problem I might say. I will bind it myself. However the Cache object is not serializable and you will end with an exception. No again.
javax.naming.CommunicationException [Root exception is java.io.NotSerializableException:
  • MultiplexedJBossCacheRegionFactory is the most recommended solution. What it does is to create multiple Caches managed by a CacheManager. Remember: you can still have multiple cache regions with different eviction policies even in a single cache so the reason for multiple caches seems an extreme case for me such as: having different passivations or transport options. Note that this CacheManager is created by hibernate and is not exposed to jmx. If you want to have a clustering environment with not much fuss you will end up with jboss default cache manager which also creates several Cache’s of it’s own.
  • JndiMultiplexedJBossCacheRegionFactory seems then a wises choice as it will let you connect/use the existing CacheManager created by jboss (I will discuss configuration issues later).

Configuration

Here are some example configurations for the cases described above.

treecache.xml for the SharedJbossCacheRegionFactory

You have to put it somewhere in the classpath root, for instance in your .har file. The following example is local, does not uses jgroups and has a special region for timestamps.

<pre lang="xml">
<?xml version="1.0" encoding="UTF-8"??>
<jbosscache xmlns="urn:jboss:jbosscache-core:config:3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	
	<locking concurrencylevel="500" isolationlevel="REPEATABLE_READ" lockacquisitiontimeout="20000" lockparentforchildinsertremove="false" nodelockingscheme="mvcc" uselockstriping="true" writeskewcheck="false"></locking>

	
	<transaction synccommitphase="false" syncrollbackphase="false" transactionmanagerlookupclass="org.jboss.cache.transaction.GenericTransactionManagerLookup"></transaction>

	
	<jmxstatistics enabled="true"></jmxstatistics>

	
	<startup regionsinactiveonstartup="true"></startup>

	
	<shutdown hookbehavior="DEFAULT"></shutdown>

	
	<listeners asyncpoolsize="1" asyncqueuesize="100000"></listeners>

	
	<invocationbatching enabled="false"></invocationbatching>

	
	<serialization marshallerclass="org.jboss.cache.marshall.VersionAwareMarshaller" objectinputstreampoolsize="12" objectoutputstreampoolsize="14" uselazydeserialization="false" useregionbasedmarshalling="false" version="3.0.0"></serialization>

	
	<eviction wakeupinterval="500">
		<default algorithmclass="org.jboss.cache.eviction.LRUAlgorithm" eventqueuesize="200000">
			<property name="maxNodes" value="5000"></property>
			<property name="timeToLive" value="40000"></property>
		</default>

		<region algorithmclass="org.jboss.cache.eviction.NullEvictionAlgorithm" name="/TS">
		</region>
	</eviction>
</jbosscache>

-jboss-beans.xml deployement

Of a cache which cannot be bound to jndi and passed to SharedJbossCacheRegionFactory, also local:

<pre lang="xml">
<?xml version="1.0" encoding="UTF-8"??>
<deployment xmlns="urn:jboss:bean-deployer:2.0">

   
   <bean class="org.jboss.cache.config.Configuration" name="DiapasonCacheConfig">
      <property name="runtimeConfig">
         <bean class="org.jboss.cache.config.RuntimeConfig">
            <property name="transactionManager">
               <inject bean="jboss:service=TransactionManager" property="TransactionManager"></inject>
            </property>
            
         </bean>
      </property>

      <property name="multiplexerStack">udp</property>
      <property name="clusterName">Diapason-EntityCache</property>
      <property name="isolationLevel">REPEATABLE_READ</property>
      <property name="cacheMode">LOCAL</property>
      <property name="stateRetrievalTimeout">15000</property>
      <property name="syncReplTimeout">20000</property>
      <property name="lockAcquisitionTimeout">15000</property>
      <property name="exposeManagementStatistics">true</property>
   </bean>


   
   <bean class="org.jboss.cache.DefaultCacheFactory" name="DefaultCacheFactory">      
      <constructor factoryclass="org.jboss.cache.DefaultCacheFactory" factorymethod="getInstance"></constructor>
   </bean>

   
   <bean class="org.jboss.cache.Cache" name="DiapasonCache">
      <constructor factorymethod="createCache">
          <factory bean="DefaultCacheFactory"></factory>
          <parameter class="org.jboss.cache.config.Configuration"><inject bean="DiapasonCacheConfig"></inject></parameter>
          <parameter class="boolean">false</parameter>
      </constructor>
   </bean>

   
   <bean class="org.jboss.cache.jmx.CacheJmxWrapper" name="DiapasonCacheJmxWrapper">
      <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="jboss.cache:service=DiapasonTreeCache", exposedInterface=org.jboss.cache.jmx.CacheJmxWrapperMBean.class, registerDirectly=true)</annotation>
      <constructor>
          <parameter><inject bean="DiapasonCache"></inject></parameter>
      </constructor>
   </bean>

</deployment> 

MultiplexedJBossCacheRegionFactory

No config is needed in this case as hibernate will use 2 files jbc2-configs.xml and jgroups-stacks.xml both found in hibernate-jbosscache2.jar. Of course if you want to take advantage of the configurability of Jboss Cache you will have to take these files and adapt them to your need.

JndiMultiplexedJBossCacheRegionFactory

This option will give you most of the things you want and can be configured as following:

<pre lang="xml"><property name="cacheRegionFactoryClass">org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory</property>
<property name="deployedCacheManagerJndiName">java:/CacheManager</property>

This will make use of the existing CacheManager which is registered to JNDI. However if using the “default” configuration for jboss this is not the case. You will need to copy jboss-cache-manager.sar and jgroups-channelfactory.sar from the all/deploy/cluster to default/deploy/cluster along with an extra jar for pojo cache (jbosscache-pojo.jar, still don’t know the use of that).

In order to configure your cache you will need to edit the jboss-cache-manager-jboss-beans.xml file notably the optimistic-entity entry which hibernate will use.

Conclusions

You might ask: why use jboss cache after all? it does seem a bit too complicated. I think you can find at least the following benefits:

  • Configurability related to cache regions. This seems the most interesting benefit from my point of view, can be done in any of the previous configs and does not require a CacheManager or clustering.This is where you can configure various eviction policies. You might want for instance some data to be evicted much slower than other or some data never to evicted. This means of course some mapping (.hbm) changes in case of entities consisting in adding the region attribute to the cache part of the mapping and some code change in case of queries.
  • JMX is of great use. First, it allows to see that the eviction configured really works and second it shows lock problems which unfortunately where a problem in previous jboss cache versions (as in jboss 4.2.2 GA). Let’s hope it will no longer be the case.
  • Of least importance for most people it will be clustering. But even if initially it might be of reduced importance it’s good to know if you ever need it support is already there and only some configuration is required

Finally here are some links which I read a lot of times in the process of testing these configurations and are the base for this article which intended to be much more shorter: