设置对象定时过期的包装类
针对于,需要定时过期的单例对象
/**
* 用来存储需要定时过期的对象
*/
public class ExpiredObject<T> {
private long time;
private T cacheObject;
// 超时限制,1分钟
private static final long TIMEOUT = 1000 * 60;
public ExpiredObject(T cacheObject) {
//初始化创建时间
this.cacheObject = cacheObject;
this.time = System.currentTimeMillis();
}
/**
* 是否已经超时
* ture 已经超时
* false 还没超时
* @return bool
*/
public boolean isExpired() {
//当前时间戳 - 记录的时间戳 > 超时时间
return System.currentTimeMillis() - this.time > TIMEOUT;
}
public void updateCache(T cacheObject){
this.time = System.currentTimeMillis();
this.cacheObject = cacheObject;
}
public T getCacheObject() {
if(isExpired()) return null;
return cacheObject;
}
public void setCacheObject(T cacheObject) {
this.cacheObject = cacheObject;
}
public long getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
使用
//初始化
private final static HashMap<String,ExpiredObject<ConnectFactory>> connectInstance = new HashMap<>();
//保存
ExpiredObject<ConnectFactory> connectFactoryExpiredObject = new ExpiredObject<>(connectObject);
connectInstance.put(key,connectFactoryExpiredObject);
// 使用
connectObject = connectInstance.containsKey(key)? connectInstance.get(key).getCacheObject() : null;//先从缓存中进行获取