/* ================================================================== * Created [2009-4-27 下午11:32:55] by Jon.King * ================================================================== * TSS * ================================================================== * mailTo:jinpujun@hotmail.com * Copyright (c) Jon.King, 2009-2012 * ================================================================== */ package com.jinhe.tss.core.cachepool.container; import java.util.List; import com.jinhe.tss.core.cachepool.Cacheable; import com.jinhe.tss.core.cachepool.CacheableKey; /** * <p> AbstractPoolContainer.java </p> * * @author Jon.King 2007-1-3 * */ public abstract class AbstractPoolContainer implements IPoolContainer { protected String name; public AbstractPoolContainer(String name) { this.name = name; } public abstract Cacheable get(Object key); public Cacheable getByAccessMethod(int accessMethod){ Cacheable item = null; List<CacheableKey> keys = getKeys(); switch(accessMethod){ case ACCESS_LRU: long lastAccessed = 999999999; for(CacheableKey key : keys){ Cacheable temp = get(key); long life = System.currentTimeMillis() - temp.getAccessed(); if(life < lastAccessed){ lastAccessed = life; item = temp; // 找出最近使用的 } } break; case ACCESS_LFU: int minHit = 999999999; for(CacheableKey key : keys){ Cacheable temp = get(key); if(minHit < temp.getHit()){ minHit = temp.getHit(); item = temp; // 找出最不常使用的 } } break; case ACCESS_RANDOM: item = get(keys.get((int)(keys.size() * Math.random()))); // 随机 break; case ACCESS_FIFO: item = get(keys.get(0)); break; case ACCESS_LIFO: default: item = get(keys.get(keys.size() - 1)); } return item; } public Cacheable removeByAccessMethod(int accessMethod){ Cacheable o = getByAccessMethod(accessMethod); return remove(o.getKey()); } public abstract Cacheable put(Object key, Cacheable value); public abstract Cacheable remove(Object key); public abstract List<CacheableKey> getKeys(); public abstract int size(); public abstract void clear(); public String toString(){ StringBuffer sb = new StringBuffer("\n--------------------------(" + name + ")池中数据项列表 -----------------------\n"); for(CacheableKey key : getKeys()){ Cacheable cacheableItem = get(key); if(cacheableItem != null) { Object value = cacheableItem.getValue(); sb.append("key : ").append(key.getKey()).append(" , value : ").append(value).append("\n"); } } return sb.append("------------------------------------------------------------------------------").toString(); } }