public class CacheManager {
private static Map<String, CacheData> cache = new ConcurrentHashMap();
public CacheManager() {
}
public static <T> void set(String key, T t) {
cache.put(key, new CacheManager.CacheData(t, 0L));
}
public static <T> void set(String key, T t, long expire) {
cache.put(key, new CacheManager.CacheData(t, expire));
}
public static <T> T get(String key) {
CacheManager.CacheData<T> data = (CacheManager.CacheData)cache.get(key);
if (null == data) {
return null;
} else if (data.isExpire()) {
remove(key);
return null;
} else {
return data.getData();
}
}
public static void remove(String key) {
cache.remove(key);
}
public static void removeAll() {
cache.clear();
}
static {
Timer t = new Timer();
t.schedule(new CacheManager.ClearTimerTask(cache), 0L, 60000L);
}
private static class ClearTimerTask extends TimerTask {
Map<String, CacheManager.CacheData> cache;
public ClearTimerTask(Map<String, CacheManager.CacheData> cache) {
this.cache = cache;
}
public void run() {
Set<String> keys = this.cache.keySet();
Iterator var2 = keys.iterator();
while(var2.hasNext()) {
String key = (String)var2.next();
CacheManager.CacheData<?> data = (CacheManager.CacheData)this.cache.get(key);
if (data.expireTime > 0L && data.expireTime <= Calendar.getInstance().getTimeInMillis()) {
this.cache.remove(key);
}
}
}
}
private static class CacheData<T> {
private T data;
private long expireTime;
public CacheData(T t, long expire) {
this.data = t;
if (expire <= 0L) {
this.expireTime = 0L;
} else {
this.expireTime = Calendar.getInstance().getTimeInMillis() + expire;
}
}
public boolean isExpire() {
if (this.expireTime <= 0L) {
return false;
} else {
return this.expireTime <= Calendar.getInstance().getTimeInMillis();
}
}
public T getData() {
return this.data;
}
}
}
提供了基本的缓存增删、过期等方法,使用于单机情况,测试使用