如何使用compute()将foreach方法更改为原子方式工作

xvw2m8pv  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(177)

有人知道我该如何将下面的操作更改为原子操作吗?这个count变量是一个hashmap<string,integer>,我需要使用compute方法(存在于map对象上)使这个代码线程安全。下面的第一个代码段是运行良好的旧代码,但它不是线程安全的。

PageParser.Result result = parserFactory.get(url).parse();
for (Map.Entry<String, Integer> e : result.getWordCounts().entrySet()) {
    if (counts.containsKey(e.getKey())) {
        counts.put(e.getKey(), e.getValue() + counts.get(e.getKey()));
    } else {
        counts.put(e.getKey(), e.getValue());
    }
}

下面的代码是我尝试使用compute(原子)方法所做的,但是它不起作用。

PageParser.Result result = parserFactory.get(url).parse();
for (ConcurrentMap.Entry<String, Integer> e : result.getWordCounts().entrySet()) {
    counts.compute(e.getKey(), (k, v) -> {
        if (counts.containsKey(k)) {
            return counts.put(k, v + counts.get(k));
        } else {
            return counts.put(k, v);
        }
    });
}

不要注意concurrentmap而不是map,我在第二部分中更改了它,但错误与此无关。我需要修改被注解的代码来使用计算,但是我不能让它工作。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题