Are size(), put(), remove(), get() atomic in Java synchronized HashMap?

旧巷老猫 提交于 2019-12-05 04:32:44

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");
}

A HashMap is not guaranteed to have atomic operations. Calling any of its methods from different threads (even size()) may corrupt the map. However, a map obtained using Collections.synchronizedMap will have each call synchronized (and hence thread-safe).

However, you may need higher-level synchronization. For instance, if you test whether a key is present, read the size, or otherwise access something from the map and then do something else with the map based on the result, the map may have changed between the two calls. In that case, you need a synchronized block to make the entire transaction atomic, rather than a synchronized map (that just makes each call atomic).

The map itself is synchronized, not some internal locks. Running more than one operation on the map does require a synchronized block. In any event, if you are using a JDK 1.6 or greater, you should consider using ConcurrentHashMap

ConcurrentHashMap is optimal when you need to ensure data consistency, and each of your threads need a current view of the map. If performance is critical, and each thread only inserts data to the map, with reads happening less frequently, then use the path you've outlined. That said, performance may only be poorer when only a single thread accesses a ConcurrentHashMap at a time, but significantly better when multiple threads access the map concurrently.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!