The Dynamic Cache is part of the IBM solution for improving performance of J2EE web applications running within Web Sphere Application Server. This program describes the easy and simple way to implement the Dynamic Cache for caching objects and demonstrates the dynamic cache implementation in web application and performance improvement gained by applying dynamic caching to a typical enterprise Web application.
import java.util.HashMap; import java.util.Iterator; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import com.ibm.websphere.cache.EntryInfo; import com.ibm.websphere.cache.DistributedMap; import java.io.ObjectStreamException; import java.io.Serializable; public final class DynamicCache implements Serializable { static String jndiName ="services/DynaCache"; /** * private variable holds Distributed map of Dynamic cache */ private DistributedMap dynaCache = null; /** * static EntitlementCache instance variable */ private static DynamicCache dynamicCache = new DynamicCache(jndiName); private DynamicCache(){ super(); } private DynamicCache(String jndiName) { initializeDynamicCache(jndiName); } public void initializeDynamicCache(String jndiName){ try { Context context = new InitialContext(); dynaCache = (DistributedMap)context.lookup(jndiName); } catch (NamingException e) { e.printStackTrace(); } } public static DynamicCache getInstanceForDynaCache(){ if(dynamicCache==null){ dynamicCache=new DynamicCache(jndiName); return dynamicCache; }else{ return dynamicCache; } } /** * putInDynamicCache is used put cached objects into Distributed Map */ public synchronized void putInDynamicCache(String key, String keyValue,int sharingPolicy,int timeToLive) { dynaCache.put(key, keyValue,1,timeToLive*60,sharingPolicy,null); } /** * getFromDynamicCache is used return the CachedObject for the application */ public String getFromDynamicCache(String key) { String keyValue = null; if(dynaCache != null && dynaCache.containsKey(key)) { keyValue = (String)dynaCache.get(key); } return keyValue; } /** * removeFromDynamicCache is used remove the CachedObject for the application */ public void removeFromDynamicCache(String key) { if(dynaCache != null && dynaCache.containsKey(key)) { dynaCache.remove(key); } } }