Java中的size(),put(),remove(),get()原子同步HashMap? [英] Are size(), put(), remove(), get() atomic in Java synchronized HashMap?

查看:120
本文介绍了Java中的size(),put(),remove(),get()原子同步HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Java Map声明为

  Map< String,String> map = Collections.synchronizedMap(new HashMap< String,String>()); 

来处理并发问题,并在地图上同步所有操作。但是,当操作是原子操作时,我读取 synchronizedMap 时不需要同步。我检查了Java API,并且HashMap的文档似乎没有提及哪些是原子的,所以我不确定哪些是原子的。



我正在同步以下是对地图的调用:

  map.size()

map.put()

map.remove()

map.get()



但是如果有些是原子的,似乎同步并不是必需的。哪个是原子的?

解决方案

同步映射顾名思义是同步的。它的每一个操作都是原子的。



你可以认为你的同步映射的每个方法都是用<$ c

请注意,虽然单个操作是原子操作,但如果将它们组合起来,它们不再是原子操作,例如:

 字符串值= map.get(key); 
map.put(key,value +2);

不等同于您的自定义同步代码:

  synchronized(map){
String value = map.get(key);
map.put(key,value +2);
}

而是:

  synchronized(map){
String value = map.get(key);
}
同步(地图){
map.put(key,value +2);
}


I am declaring a Java Map as

Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());

to deal with the concurrency issues, and synchronizing on the map for all the operations on it. However, I read that synchronization isn't necessary on a synchronizedMap when the operations are atomic. I checked the Java API and the documentation of HashMap doesn't seem to mention which are atomic, so I'm not sure which are.

I'm synchronizing on the following calls to the map:

map.size()

map.put()

map.remove()

map.get()

But if some are atomic, it seems synchronization isn't necessary for these. Which are atomic?

解决方案

A synchronized map as the name suggests is synchronized. Every operation on it is atomic in respect to any other operation on it.

You can think of it as if every method of your synchronized map is declared with a synchronized keyword.

Please bear in mind that although individual operations are atomic, if you combine them they're no longer atomic, for instance:

String value = map.get("key");
map.put("key", value+"2");

is not equivalent to your custom synchronized code:

synchronized (map) {
    String value = map.get("key");
    map.put("key", value+"2");
}

but rather:

synchronized (map) {
    String value = map.get("key");
}
synchronized (map) {
    map.put("key", value+"2");
}

这篇关于Java中的size(),put(),remove(),get()原子同步HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆