码迷,mamicode.com
首页 > 其他好文 > 详细

本地缓存设计

时间:2018-04-16 22:20:27      阅读:16      评论:0      收藏:0      [点我收藏+]

标签:port   value   java   super   cache   hash   import   ==   remove   

被问到本地缓存设计,有点蒙,事后反应过来,何必一个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;
}
}

}

思路清晰了,就好写了,借鉴了下别人的思路,有错误欢迎指出。

本地缓存设计

标签:port   value   java   super   cache   hash   import   ==   remove   

原文地址:https://www.cnblogs.com/anyehome/p/8858848.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!