2013-07-17 29 views
0

我可以使用isKeyInCache並將putIfAbsent方法替換爲ehcache嗎?我可以使用isKeyInCache並將putIfAbsent方法替換爲ehcache嗎?

這裏是我的測試代碼,性能差別很大,

// putIfAbsent 
time = System.nanoTime(); 
ehcache.putIfAbsent(new Element(assetUid, asset)); 
estimated = System.nanoTime(); 
System.out.println(estimated - time); 

// isKeyInCache and put 
time = System.nanoTime(); 
if (!ehcache.isKeyInCache(assetUid)) { 
    ehcache.put(new Element(assetUid, asset)); 
} 
estimated = System.nanoTime(); 
System.out.println(estimated - time); 

和控制檯輸出

1693409 
18235 

或者你有其他的建議?謝謝

回答

2

簡短的回答是,putIfAbsent()將尊重鎖和競爭條件(換句話說就是在某處同步),以確保條目確實只在沒有任何東西存在的情況下進行放置......或者當前正在被另一個線程寫入etc ...

調用isKeyInCache不會。 From http://ehcache.org/apidocs/net/sf/ehcache/Ehcache.html#isKeyInCache(java.lang.Object): 「一種便宜的檢查,看看密鑰是否存在於緩存中 這種方法不是同步的,有可能一個元素可能存在於緩存中,並在檢查到達之前被移除,反之亦然。由於沒有對元素的狀態進行斷言,因此元素可能已過期,但此方法仍然返回true。「

這也解釋了時間差......

從上面的,這真的取決於你的使用情況... ...你的發言:「一個元素可以在緩存中,且有可能在支票到達之前被移除,反之亦然「?如果是,請使用isKeyInCache()檢查... 如果您希望在此檢查期間確定,請使用putIfAbsent()...

相關問題