开发者

Replace ConcurrentHashMap with EnumMap

开发者 https://www.devze.com 2023-02-04 18:34 出处:网络
All the while, I am using ConcurrentHashMap, if I want to achieve the following. Able to iterate the map without throwing ConcurrentModificationException, while another thread is modifying the map c

All the while, I am using ConcurrentHashMap, if I want to achieve the following.

  1. Able to iterate the map without throwing ConcurrentModificationException, while another thread is modifying the map content.
  2. Allow two modification, by two threads at the same time.

Sometime, I use enum as key, and from EnumMap开发者_如何学JAVA Javadoc, I realize,

Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.

Hence, is it safe for me to replace

Map<Country, String> map =  new ConcurrentHashMap<Country, String>();

with

Map<Country, String> map =  Collections.synchronizedMap(new EnumMap<Country, String>(Country.class));

I know there is no putIfAbsent in EnumMap, but that is OK for me at this moment as I do not require it.


You can't do it for two reasons:

  1. Lack of synchronization may cause memory visibility effects (since iterators of Collections.synchronizedMap are not synchronized).
  2. Contract of Iterator would be broken - you may get NoSuchElementException when calling next() after hasNext() returned true.
0

精彩评论

暂无评论...
验证码 换一张
取 消