import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set;
public class CacheManager {
public static void main(String agrs[]) {
CacheConfiguration config = new CacheConfiguration();
config.setIsForever(false);
config.setBeginTime(new Date().getTime());
config.setDurableTime(1);
CacheManager cacheManager = CacheManager.getInstance();
String value = "this a cache ...";
String key = "cache";
cacheManager.add(key, value, config);
String results = (String) cacheManager.get(key);
System.out.println(results);
try {
Thread.sleep(1000 * 60 + 1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
String results1 = (String) cacheManager.get(key);
System.out.println(results1);
}
private static Map cacheMap = new HashMap();
private static Map cacheConfigMap = new HashMap();
private static CacheManager cacheManager = null;
private CacheManager() {
}
public static CacheManager getInstance() {
if (cacheManager == null) {
cacheManager = new CacheManager();
//at the same time ,it should start up the monit thread
ClearThread thread = new ClearThread();
thread.start();
}
return cacheManager;
}
public Object get(Object key) {
return cacheMap.get(key);
}
public boolean add(Object key, Object value, CacheConfiguration config) {
cacheMap.put(key, value);
cacheConfigMap.put(key, config);
return true;
}
public boolean remove(Object key) {
cacheMap.remove(key);
cacheConfigMap.remove(key);
return true;
}
private static class ClearThread extends Thread {
public void run() {
while (true) {
Set tempSet = new HashSet(); //保存待删除的key
Set configSet = cacheConfigMap.keySet();
Iterator it = configSet.iterator();
while (it.hasNext()) {
Object key = it.next();
CacheConfiguration configs = (CacheConfiguration) cacheConfigMap.get(key);
if (!configs.isIsForever()) {
if ((new Date().getTime() - configs.getBeginTime()) >= configs.getDurableTime() * 60 * 1000) {
tempSet.add(key);
}
}
}
Iterator tempIt = tempSet.iterator();
while (tempIt.hasNext()) {
Object key = tempIt.next();
cacheMap.remove(key);
cacheConfigMap.remove(key);
}
try {
Thread.sleep(1000 * 60L);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
}
class CacheConfiguration implements Serializable {
private long beginTime;
private boolean isForever = false;
private int durableTime;
public CacheConfiguration() {
// read cache property from configure file
}
public long getBeginTime() {
return beginTime;
}
public void setBeginTime(long beginTime) {
this.beginTime = beginTime;
}
public boolean isIsForever() {
return isForever;
}
public void setIsForever(boolean isForever) {
this.isForever = isForever;
}
public int getDurableTime() {
return durableTime;
}
public void setDurableTime(int durableTime) {
this.durableTime = durableTime;
}
}