How to use custom servlet cache instance for Custom Java Objects

In the Storing custom java objects in Dynacache using CachableCommand entry i talked about how to use the DynaCache for storing the custom java object, similarly you can use the DynaCache for caching output of a portlet or servlet

By default websphere application server creates one instance of cache(you can think of cache instance as bucket) baseCache and that cache instance is used for storing all the custom java objects, output of servlet, output of portlet. But what if you want to have more granular control over the cache instance. Ex. you want to cache say up to 2000 instances of custom java object or you want to make sure that only 10mb size is used for storing servlet output. In order to solve those advanced use cases you should create separate cache instance.

I wanted to try how to use a separate cache instance for my storing custom java object, so first i went to WAS Admin Console and i did define a new Servlet cache instance like this



When you create a new cache instance you can define things like the JNDI name where the instance would be bound, also Cache size, which means how many objects would be stored in the cache. In my case i am using default cache size of 2000 and then i am setting JNDI name for the cache instance to be services/cache/samplecache.

I can configure my Sample application for storing custom java object to use the services/cache/samplecache by making one change in the cachespec.xml file like this


<?xml version="1.0" ?>
<!DOCTYPE cache SYSTEM "cachespec.dtd">
<cache>
<cache-instance name="services/cache/samplecache">
<cache-entry>
<class> command</class>
<sharing-policy>not-shared</sharing-policy>
<name> com.webspherenotes.cache.CacheableContact.class</name>
<cache-id>
<component type="method" id="getContactId">
<required>true</required>
</component>
<priority>1</priority>
<timeout>180</timeout>
</cache-id>
</cache-entry>
</cache-instance>
</cache>


You can configure the cache-entry to use different cache-instance by enclosing it in cache-instance element where value of name attribute should be equal to the JNDI name where the cache instance is bound, the same name that you used while configuring the cache instance

After making the change i did execute the servlet so that the CacheableContact objects is set in cache, now i can see that instance using cache monitor