public class CacheTimerHandler {
private static final long SECOND_TIME = 1000;//默认过期时间 20秒
private static final int DEFUALT_VALIDITY_TIME = 20;//默认过期时间 20秒
private static final Timer timer ;
private static final SimpleConcurrentMap<String, CacheEntity> map;
static{
timer = new Timer();
map = new SimpleConcurrentMap<String, CacheEntity>(new HashMap<String, CacheEntity>(1<<18));
}
/**
* 增加缓存对象
* @param key
* @param ce
*/
public static void addCache(String key, CacheEntity ce){
addCache(key, ce, DEFUALT_VALIDITY_TIME);
}
/**
* 增加缓存对象
* @param key
* @param ce
* @param validityTime 有效时间
*/
public static synchronized void addCache(String key, CacheEntity ce, int validityTime){
map.put(key, ce);
//添加过期定时
timer.schedule(new TimeoutTimerTask(key), validityTime * SECOND_TIME);
}
/**
* 获取缓存对象
* @param key
* @return
*/
public static synchronized CacheEntity getCache(String key){
return map.get(key);
}
/**
* 检查是否含有制定key的缓冲
* @param key
* @return
*/
public static synchronized boolean isConcurrent(String key){
return map.containsKey(key);
}
/**
* 删除缓存
* @param key
*/
public static synchronized void removeCache(String key){
map.remove(key);
}
/**
* 获取缓存大小
* @param key
*/
public static int getCacheSize(){
return map.size();
}
/**
* 清除全部缓存
*/
public static synchronized void clearCache(){
if(null != timer){
timer.cancel();
}
map.clear();
System.out.println("clear cache");
}
static class TimeoutTimerTask extends TimerTask{
private String ceKey ;
public TimeoutTimerTask(String key){
this.ceKey = key;
}
@Override
public void run() {
CacheTimerHandler.removeCache(ceKey);
System.out.println("remove : "+ceKey);
}
}
}
timer方式有点是适用性更强,因为每个缓存的过期时间都可以独立配置的;ist只能适用 于缓存时间都一样的线性过期。从性能开销方面,因为timer是与缓存对象数量成正比的,在缓存量很大的时候,在缓存时间内系统开销也随之提高;而 list方式只要一个线程管理过期清理就可以了。ReadWriteLock 请参考http://www.blogjava.net/xylz/archive/2010/07/14/326080.html
在这里程序还有更好的方式来实现
使用FutureTask来获取任务,这样避免了每次执行相同计算工作,例如
一个线程在执行map.put(5),此时第二个线程也是执行map.put(5),或者执行一系列的计算,目的是get(5)这个操作,可是这个操作已经在进行了,现在我们需要一种先进行判断的模式,先判断是否有线程正在执行这个操作,如果有我们就不在执行,这样可以避免重覆的开销,有线程在执行这个操作那就继续等待其执行完,而不用再去执行一次