我正在编写一个缓存实现 - 如果它存储在商店中超过5分钟,它将使存储的项目到期。在这种情况下,它应该从源刷新,否则应该返回缓存的副本。
以下是我写的内容 - 它有任何设计缺陷吗?特别是get
部分?
public class Cache<K,V> {
private final ConcurrentMap<K,TimedItem> store ;
private final long expiryInMilliSec ;
Cache(){
store = new ConcurrentHashMap<K, TimedItem>(16);
expiryInMilliSec = 5 * 60 * 1000; // 5 mins
}
Cache(int minsToExpire){
store = new ConcurrentHashMap<K, TimedItem>(16);
expiryInMilliSec = minsToExpire * 60 * 1000;
}
// Internal class to hold item and its 'Timestamp' together
private class TimedItem {
private long timeStored ;
private V item ;
TimedItem(V v) {
item = v;
timeStored = new Date().getTime();
}
long getTimeStored(){
return timeStored;
}
V getItem(){
return item;
}
public String toString(){
return item.toString();
}
}
// sync on the store object - its a way to ensure that it does not interfere
// with the get method's logic below
public void put(K key, V item){
synchronized(store){
store.putIfAbsent(key, new TimedItem(item));
}
}
// Lookup the item, check if its timestamp is earlier than current time
// allowing for the expiry duration
public V get(K key){
TimedItem ti = null;
K keyLocal = key;
boolean refreshRequired = false;
synchronized(store){
ti = store.get(keyLocal);
if(ti == null)
return null;
long currentTime = new Date().getTime();
if( (currentTime - ti.getTimeStored()) > expiryInMilliSec ){
store.remove(keyLocal);
refreshRequired = true;
}
}
// even though this is not a part of the sync block , this should not be a problem
// from a concurrency point of view
if(refreshRequired){
ti = store.putIfAbsent(keyLocal, new TimedItem(getItemFromSource(keyLocal)) );
}
return ti.getItem();
}
private V getItemFromSource(K key){
// implement logic for refreshing item from source
return null ;
}
public String toString(){
return store.toString();
}
}
答案 0 :(得分:1)
鉴于你试图手动同步事物(猜测)你似乎没有彻底测试过,我会说你有98%的可能存在错误。您是否有充分理由不使用已建立的缓存库提供的功能,例如Ehcache的SelfPopulatingCache?
答案 1 :(得分:0)
文档说replace
是原子的,所以我会做这样的事情:
public V get(K key){
TimedItem ti;
ti = store.get(key);
if(ti == null)
return null;
long currentTime = new Date().getTime();
if((currentTime - ti.getTimeStored()) > expiryInMilliSec){
ti = new TimedItem(getItemFromSource(key));
store.replace(key, ti);
}
return ti.getItem();
}