英文:
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<Object,Long> syncMap = Collections.synchronizedMap(normalHashMap);
Runnable mapOperations = () -> {
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 "key"
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<Object,Long> syncMap = Collections.synchronizedMap(normalHashMap);
Also, you don't need a synchronized { }
block if you use the SynchronizedMap
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论