0

我可以使用 isKeyInCache 和 put 方法替换 ehcache 上的 putIfAbsent 吗?

这是我的测试代码,性能差异很大

// 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

或者你有其他建议?谢谢

4

1 回答 1

2

简短的回答是 putIfAbsent() 将遵守锁和竞争条件(换句话说,同步某处)以确保只有在没有任何内容时才确实放置条目......或当前由另一个线程写入等......

调用 isKeyInCache 不会。来自http://ehcache.org/apidocs/net/sf/ehcache/Ehcache.html#isKeyInCache(java.lang.Object):“一种廉价的检查以查看缓存中是否存在密钥。此方法不同步。一个元素可能存在于缓存中并在检查到达之前被删除,反之亦然。由于没有对元素的状态进行断言,因此元素可能已过期,但此方法仍然返回真的。”

这解释了时间差异......

从上面看,这真的取决于你的用例......你能接受这样的说法吗:“一个元素可能存在于缓存中并在检查到达之前被删除,反之亦然”?如果是,请使用 isKeyInCache() 检查...如果您希望在检查期间确定性,请坚持使用 putIfAbsent()...

于 2013-07-17T21:24:01.627 回答