更新时间:2023-12-05 15:48:58
下面是相当于你的。我已经压力测试了一些与成千上万的线程并发访问它:它的工作原理,与一些重试(循环)执行(显然,你永远不能证明正确性在并发世界中的测试)。
You could make it a little shorter with the code below which is equivalent to yours. I have stress tested it a little with thousands of threads accessing it concurrently: it works as expected, with a number of retries (loops) being performed (obviously, you can never prove correctness with testing in the concurrent world).
public void insertOrReplace(String key, String value) {
for (;;) {
String oldValue = concurrentMap.putIfAbsent(key, value);
if (oldValue == null)
return;
final String newValue = recalculateNewValue(oldValue, value);
if (concurrentMap.replace(key, oldValue, newValue))
return;
}
}