java - 自动整数线程澄清

标签 java multithreading concurrency concurrenthashmap

我有以下代码,

private final Map<String, AtomicInteger> wordCounter = new ConcurrentHashMap<>();

AtomicInteger count = wordCounter.get(word);
if (count == null) {
    if ((count = wordCounter.putIfAbsent(word, new AtomicInteger(1))) == null) {
        continue;
    }
}
count.incrementAndGet();

我正在 IF 条件下检查 count == null。据我所知,AutomicInteger 中的操作是线程安全的。是否有必要使用其中一种锁定机制来锁定 count 实例?

最佳答案

上面的代码无需任何额外的锁定即可工作,但可以简化为以下惯用形式

// If word doesn't exist, create a new atomic integer, otherwise return the existing
wordCounter.computeIfAbsent(word, k -> new AtomicInteger(0))
    .incrementAndGet();  // increment it

您的代码看起来有点像 double checked locking ,因为 putIfAbsent() 在空检查之后使用,以避免覆盖可能由另一个线程放在那里的值。然而,该路径会创建一个额外的 AtomicInteger,而 DCL 不会发生这种情况。额外的对象可能并不重要,但它确实使解决方案变得不那么“纯粹”。

关于java - 自动整数线程澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501447/

相关文章:

java - 从 DefaultTableModel 中删除后使用该行的数据

C# 线程生成参数传递

java - 同步方法上的死锁

c++ - 如何在 std::thread 中正确嵌入 QEventLoop?

java - Android:新线程在完成执行后会停止吗?

java - 哪种是杀死线程的最简洁和/或最有效的方法

java - 如何推迟Spring应用程序在Eureka中的注册,直到应用程序完全初始化?

JavaFX Print WebView as PDF 仅打印一页

java - 找出java中LSD计数排序程序中出现java.lang.NoClassDefFoundError的原因

java - 在 Timer.Schedule() 中抛出空指针异常;