package com.amarsoft.app.base.businessobject; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class BusinessObjectCache{ private int cacheSize=0; private Map cacheObjects = null; private Map hitInfoMap = null; public boolean isCached(String cacheKey){ return cacheObjects.containsKey(cacheKey); } public BusinessObjectCache(int cacheSize){ this.cacheSize=cacheSize; this.cacheObjects = new HashMap(cacheSize); this.hitInfoMap=new HashMap(cacheSize); } public Map getCacheObjects(){ return cacheObjects; } public Object getCacheObject(String cacheKey){ Object o = this.cacheObjects.get(cacheKey); if(o!=null){//更新访问时间和次数 HitInfo hitInfo=this.hitInfoMap.get(cacheKey); hitInfo.hitCount++; hitInfo.lastHitTime= new Date().getTime(); } return o; } public void clear(int clearCount){ List l=new ArrayList(); l.addAll(hitInfoMap.values()); Collections.sort(l); for(int i=0;icacheSize){ clear(this.cacheSize/10); } this.cacheObjects.put(cacheKey, o); } public void clear(){ cacheObjects.clear(); hitInfoMap.clear(); } private class HitInfo implements Comparable { String key=null; long hitCount=0l; long updateTime=0l; long lastHitTime=0l; public HitInfo(String cacheKey){ key=cacheKey; hitCount = 1L; updateTime = new Date().getTime(); lastHitTime = new Date().getTime(); } public int compareTo(HitInfo hitInfo) { if(this.lastHitTimehitInfo.lastHitTime){ return 1; } else { if(this.hitCounthitInfo.hitCount){ return 1; } else { if(this.updateTimehitInfo.updateTime){ return 1; } else return 0; } } } } }