Java synchronized block vs. Collections.synchronizedMap(Java 同步块与 Collections.synchronizedMap)
问题描述
以下代码是否设置为正确同步 synchronizedMap 上的调用?
Is the following code set up to correctly synchronize the calls on synchronizedMap?
public class MyClass {
private static Map<String, List<String>> synchronizedMap = Collections.synchronizedMap(new HashMap<String, List<String>>());
public void doWork(String key) {
List<String> values = null;
while ((values = synchronizedMap.remove(key)) != null) {
//do something with values
}
}
public static void addToMap(String key, String value) {
synchronized (synchronizedMap) {
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
}
}
}
据我了解,我需要 addToMap() 中的同步块来防止另一个线程调用 remove() 或 containsKey()在我完成对 put() 的调用之前,但我不需要 doWork() 中的同步块,因为另一个线程无法进入 addToMap() 在 remove() 返回之前,因为我最初使用 Collections.synchronizedMap() 创建了地图.那是对的吗?有没有更好的方法来做到这一点?
From my understanding, I need the synchronized block in addToMap() to prevent another thread from calling remove() or containsKey() before I get through the call to put() but I do not need a synchronized block in doWork() because another thread cannot enter the synchronized block in addToMap() before remove() returns because I created the Map originally with Collections.synchronizedMap(). Is that correct? Is there a better way to do this?
推荐答案
Collections.synchronizedMap() 保证你想在地图上运行的每个原子操作都会被同步.
Collections.synchronizedMap() guarantees that each atomic operation you want to run on the map will be synchronized.
但是,在地图上运行两个(或更多)操作必须在一个块中同步.所以是的 - 你正在正确同步.
Running two (or more) operations on the map however, must be synchronized in a block. So yes - you are synchronizing correctly.
这篇关于Java 同步块与 Collections.synchronizedMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 同步块与 Collections.synchronizedMap
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
