我有一個奇怪的(至少對我來說)具有番石榴緩存的行爲。第一次擊中後,以下訪問將返回一個空對象。我沒有使用奇怪的表現,所以我無法弄清楚我做錯了什麼。 我聲明瞭以下LoadingCache:番石榴緩存在第二次打擊時返回空結果
LoadingCache<String, Vector<Location>> locations = CacheBuilder.newBuilder()
.maximumSize(100000)
.build(
new CacheLoader<String,Vector<Location>>() {
@Override
public Vector<Location> load(String key) {
return _getLocationListByTranscriptId(key);
}
});
,我只在該方法中使用它:
public Vector<Location> getLocationListByTranscriptId (String transcriptid) {
if (transcriptid.equals("TCONS_00000046")) System.out.println("tcons found, will this work?");
Vector<Location> result;
try {
result = locations.get(transcriptid);
} catch (ExecutionException e) {
System.err.println("Error accessing cache, doing the hard way");
result = _getLocationListByTranscriptId(transcriptid);
}
if (transcriptid.equals("TCONS_00000046")){
if (result.size()==0){
System.out.println("this is a problem");
return null;
}
System.out.println("this is good!");
}
return result;
}
遍歷集合輸入字符串中,我得到下面的輸出:
tcons found, will this work?
this is good!
tcons found, will this work?
this is a problem
所以,我第一次使用緩存,它可以工作,但是 A)該值未被正確存儲用於將來的訪問; B)價值重新設置爲一些奇怪的行爲。 我能做些什麼?感謝所有閱讀!
編輯: 感謝axtavt答案,我可以立即找出我編輯結果列表的位置。不知道爲什麼,我確信番石榴緩存會返回值的副本。感謝您的回答,並提供有關防禦性編程的建議。 (對不起,如果我不能評價你的答案呢)。