Java 我可以在ehcache上使用isKeyInCache和put方法replace putIfAbsent吗?

Java 我可以在ehcache上使用isKeyInCache和put方法replace putIfAbsent吗?,java,ehcache,Java,Ehcache,我可以在ehcache上使用isKeyInCache和put方法replace putIfAbsent吗 这是我的测试代码,性能差异很大 // putIfAbsent time = System.nanoTime(); ehcache.putIfAbsent(new Element(assetUid, asset)); estimated = System.nanoTime(); System.out.println(estimated - time); // isKeyInCache an

我可以在ehcache上使用isKeyInCache和put方法replace 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

或者你有其他建议?谢谢

简单的回答是putIfAbsent()将尊重锁和竞争条件(换句话说,在某个地方同步),以确保只有在没有任何内容的情况下,或者当前正在由另一个线程编写时,才确实放置条目等

呼叫isKeyInCache将不会。 发件人: “一种廉价的检查,以查看缓存中是否存在密钥。 此方法未同步。元素可能存在于缓存中,并在检查到达之前被删除,反之亦然。由于未对元素的状态进行断言,因此元素可能已过期,但此方法仍返回true。“

这就解释了时间的不同

综上所述,这实际上取决于您的用例……您能否接受这样一句话:“有可能某个元素存在于缓存中,并在检查到达它之前被删除,反之亦然”?如果是,请使用isKeyInCache()检查。。。 如果您希望在检查过程中确定,请坚持使用putIfAbsent()