被问到本地缓存设计,有点蒙,事后反应过来,何必一个Map呢,两个就可以解决了。真是当时脑子短路了。
package cache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MyCache<K, V> {
private static class ValueObject<T> {
private T value;
private long timeout;
private ValueObject(T value, long timeout) {
super();
this.value = value;
this.timeout = timeout;
}
private T getValue() {
return value;
}
private long getTimeout() {
return timeout;
}
}
public static final Map<Object, ValueObject> localCache = new ConcurrentHashMap<Object, ValueObject>();
public static Object set(Object key, ValueObject value, long timeout) {
long currentTime = System.currentTimeMillis();
ValueObject valueObject = localCache.get(key);
if (localCache.keySet().contains(key)
&& (valueObject.getTimeout() == 0 || currentTime <= valueObject.getTimeout())) {
return valueObject.getValue();
} else {
ValueObject oldValueObject = localCache.put(key, new ValueObject(value, currentTime + timeout));
return oldValueObject == null ? null : oldValueObject.getValue();
}
}
public static <T> T set(Object key, ValueObject value) {
ValueObject oldValueObject = localCache.put(key, new ValueObject(value, 0));
return (T) (oldValueObject == null ? null : oldValueObject.getValue());
}
public static <T> T get(Object key) {
long currentTime = System.currentTimeMillis();
ValueObject valueObject = localCache.get(key);
if (valueObject == null) {
return null;
}
if (valueObject.getTimeout() == 0 || currentTime <= valueObject.getTimeout()) {
return (T) valueObject.getValue();
} else {
localCache.remove(key);
return null;
}
}
}
思路清晰了,就好写了,借鉴了下别人的思路,有错误欢迎指出。