public class CacheTimerHandler { html
private static final long SECOND_TIME = 1000;//默认过时时间 20秒 java
private static final int DEFUALT_VALIDITY_TIME = 20;//默认过时时间 20秒 缓存
private static final Timer timer ; ide
private static final SimpleConcurrentMap<String, CacheEntity> map; 性能
static{ this
timer = new Timer(); spa
map = new SimpleConcurrentMap<String, CacheEntity>(new HashMap<String, CacheEntity>(1<<18)); .net
} 线程
/** htm
* 增长缓存对象
* @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)这个操做,但是这个操做已经在进行了,如今咱们须要一种先进行判断的模式,先判断是否有线程正在执行这个操做,若是有咱们就不在执行,这样能够避免重覆的开销,有线程在执行这个操做那就继续等待其执行完,而不用再去执行一次