1. To cache Java application, you have to solve all or some of those problems:

  • When should we cache?
  • How do we manage updated data?
  • How do we manage old data?
  • How do we manage concurrent access to our cache?

2. Antipattern
     a. Remove stale elements from cache.
     b. Capping the size doing something for garbage collection if memory becomes constrained.
     c.  Synchronized read/write bottleneck such as collision between readers, lockers allow shared access

package com.mth.cache;     

import java.io.*; 
import java.uitl.*; 
import com.mth.cache.ShowBoardCommand;     

public class BoardCommandCache { 
   protected String cacheKey = null; 
   public boolean cached = false; 
   private ShowBoardCommand boardCommand = null; 
   private static Hashtable boardCache = null;     

   public initialize throws IOException, DataException { 
	   synchronized(boardCache){ 
		   if(boardCache == null) { 
			   new Hashtable(); 
		   } 
	   } 
   }     

   public void invalidate(String key) { 
	   synchronized(boardCache){ 
	   	   getBoardCache().remove(key); 
	   } 
   }     

   public void execute() throws IOException, DataException { 
	   synchronized(boardCache){ 
		   try{ 
			   cached = true; 
			   Hashtable cache = getBoardCache(); 
			   if (cache == null) 
			      throw new Exception(); 
			   boardCommand = (ShowBoardCommand) cache.get(getBoard()); 
			   if(boardCommand == null){ 
				   boardCommand = new ShowBoardCommand(); 
				   boardCommand.set(getBoard()); 
				   boardCommand.execute(); 
				   cache.put(getBoard(), boardCommand); 
				   cached = false; 
			   } 
		   }catch(Throwable theException){ 
			   theException.printStackTrace(); 
		   } 
	   } 
   }     

   public String getBoard() { 
	   return cacheKey; 
   }     

   protected static Hashtable getBoardCahce(){ 
	   return boardCache; 
   } 
   //skip code... 
}
Advertisements