Caching Custom Objects

The DistributedMap and DistributedObjectCache interfaces are simple interfaces for dynamic cache. Using these interfaces J2EE applications and system components can cache and share java objects by storing references to the object in the cache.

The default dynamic cache instance is created if the dynamic cache service is enabled in the administrative console. The default instance is bound in global JNDI tree at services/cache/distributedmap.

This is the sample code that demonstrate how to use default instance of dynamic cache

public class DynaCachePortlet extends javax.portlet.GenericPortlet {
private DistributedMap distributedMap;
public void init() throws PortletException{
System.out.println("Entering DynaCachePortlet.init()");
try {
InitialContext context = new InitialContext();
distributedMap= (DistributedMap)context.lookup("services/cache/distributedmap");
System.out.println("Distributed Map " + distributedMap);

} catch (NamingException e) {
System.out.println("Exiting DynaCachePortlet.init()");
public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
// Set the MIME type for the render response
System.out.println("Entering DynaCachePortlet.doView()");
String timeOfCache = (String)distributedMap.get("timeofCache");
System.out.println("Value of timeOfCache from Cache " + timeOfCache);
if(timeOfCache == null){
SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");
timeOfCache = sd.format(new Date());
System.out.println("Setting value of TimeCache to " + timeOfCache);
distributedMap.put("timeofCache", timeOfCache);
response.getWriter().println("Hello from distributedCache " + timeOfCache);
System.out.println("Exiting DynaCachePortlet.doView()");

Actually using Dynamic Cache is pretty simple, all you have to do is lookup the distributedMap object from the cache and then you can store and retrieve objects from it as normal Hashmap.

In this sample when you go to the View mode of the portlet for first time it will store the current time in the cache and thereafter whenever you go back to the VIEW mode it will always return the same time from cache. I know this is very simple but our main goal is to learn how to use cache.

If you want you can download the DynaCache Sample portlet. Now install it on your portal and once installed try hitting it few times.

If you have not installed Cache Monitor already, install it and then go to it, you should be able to see the default instance in the instance list select it and click on go

It will display the cache statics for the dyna cache. In our case we are saving only one key in cache which is timeofCache so value of Used Entries is 1 and if you refreshed the page 3 times then the cached entry would be accessed 2 times so the value of Cache Hits would be 2

Click on Cache Contents links to go to the page that displays what all keys are stored in cache

No comments: