确保所有在Java中更新映射中单个条目的线程。

huangapple go评论68阅读模式
英文:

Ensure all threads updating a single entry in a map in Java

问题

我有一个被多个线程同时调用的方法。在这个方法中,我试图处理下面片段所解释的情况:

Map<Object, Long> syncMap = Collections.synchronizedMap(normalHashMap);

Runnable mapOperations = () -> {
    synchronized (syncMap) {
        if (MapUtils.isNotEmpty(syncMap)) {
            Object currentCount = syncMap.get(entryKey);

            // 每个线程应该执行这部分代码一次。每个线程都会带一个值,这些值将会相加,并存储在这个“key”的条目中。
            syncMap.put(key, value + valueFromThisThread);
        }
    }
};
mapOperations.run();

每个线程应该执行上述代码块一次。每个线程会带一个长整型值,这些值会相加并存储在这个“key”对应的地图条目中。

有人可以确认这是否可行?

英文:

I have a method that is called by multiple threads at the same time. Within it, I am trying to handle a scenario as explained by the snippet below:

Map&lt;Object,Long&gt; syncMap = Collections.synchronizedMap(normalHashMap);

Runnable mapOperations = () -&gt; {
    synchronized (syncMap) {
        if (MapUtils.isNotEmpty(syncMap))
        {
            Object currentCount = syncMap.get(entryKey);

            // Every thread should execute this once. Every thread brings a value and that gets added up and stored for this &quot;key&quot;
            syncMap.put(key, value + valueFromThisThread);
        }
    }
};
mapOperations.run();

Every thread should execute the block above once. Every thread brings a long value and that gets added up and stored for this one "key" entry in the map.

Can someone please confirm if this would work?

答案1

得分: 0

你的代码应该能够正常工作。另外,如果你想确保不将该字段缓存在 CPU 缓存中,你可以将其定义为 volatile,例如:

volatile Map<Object, Long> syncMap = Collections.synchronizedMap(normalHashMap);

此外,如果你使用 SynchronizedMap,就不需要 synchronized { } 块。

英文:

Your code should work fine. Additionally, if you want to make sure you don't cache the field in the CPU cache, you might want to define it as a volatile, like:

volatile Map&lt;Object,Long&gt; syncMap = Collections.synchronizedMap(normalHashMap);

Also, you don't need a synchronized { } block if you use the SynchronizedMap.

huangapple
  • 本文由 发表于 2020年8月27日 22:34:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63618333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定