LoadingCache<String, Trie> localCache = Caffeine.newBuilder()
.maximumSize(1000)
.refreshAfterWrite(TIME_OUT, TimeUnit.SECONDS)
.expireAfterWrite(TIME_OUT*2, TimeUnit.SECONDS)
.build(k -> getValue(k));
Guava refreshAfterWrite原理:
V scheduleRefresh(LocalCache.ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now, CacheLoader<? super K, V> loader) {
/**
* !entry.getValueReference().isLoading(),判断该key是不是已经在loading中,如果不是,则进入方法,如果有线程正在loading中,则直接return oldValue;获取旧值
*/
if (this.map.refreshes() && now - entry.getWriteTime() > this.map.refreshNanos && !entry.getValueReference().isLoading()) {
V newValue = this.refresh(key, hash, loader, true);
if (newValue != null) {
return newValue;
}
}
return oldValue;
}
@Nullable
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
LocalCache.LoadingValueReference<K, V> loadingValueReference = this.insertLoadingValueReference(key, hash, checkTime);
if (loadingValueReference == null) {
return null;
} else {
ListenableFuture<V> result = this.loadAsync(key, hash, loadingValueReference, loader);
if (result.isDone()) {
try {
return Uninterruptibles.getUninterruptibly(result);
} catch (Throwable var8) {
;
}
}
return null;
}
}
@Nullable
LocalCache.LoadingValueReference<K, V> insertLoadingValueReference(K key, int hash, boolean checkTime) {
LocalCache.ReferenceEntry<K, V> e = null;
this.lock();
try {
long now = this.map.ticker.read();
this.preWriteCleanup(now);
AtomicReferenceArray<LocalCache.ReferenceEntry<K, V>> table = this.table;
int index = hash & table.length() - 1;
LocalCache.ReferenceEntry<K, V> first = (LocalCache.ReferenceEntry)table.get(index);
for(e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null && this.map.keyEquivalence.equivalent(key, entryKey)) {
LocalCache.ValueReference<K, V> valueReference = e.getValueReference();
LocalCache.LoadingValueReference loadingValueReference;
if (!valueReference.isLoading() && (!checkTime || now - e.getWriteTime() >= this.map.refreshNanos)) {
++this.modCount;
loadingValueReference = new LocalCache.LoadingValueReference(valueReference);
e.setValueReference(loadingValueReference);
LocalCache.LoadingValueReference var13 = loadingValueReference;
return var13;
}
loadingValueReference = null;
return loadingValueReference;
}
}
++this.modCount;
LocalCache.LoadingValueReference<K, V> loadingValueReference = new LocalCache.LoadingValueReference();
e = this.newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
LocalCache.LoadingValueReference var18 = loadingValueReference;
return var18;
} finally {
this.unlock();
this.postWriteCleanup();
}
}
问题:如果只有refreshAfterWrite来刷新缓存,由于此方式不会过期删除缓存,只会刷新缓存,如果长时间没有线程访问缓存,则此缓存已经过期很久了,此时多个线程来请求值 ,其中一个线程去刷新值,其他线程返回旧值,由于旧值过期时间太长,会出问题。
所以需要同时使用两个方法,expire过期会删除缓存,这样其他线程就不会取旧值,而是等待新值加载。
.refreshAfterWrite(TIME_OUT, TimeUnit.SECONDS)
.expireAfterWrite(TIME_OUT*2, TimeUnit.SECONDS)