Replace ConcurrentHashMap with EnumMap
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 content. - 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:
- Lack of synchronization may cause memory visibility effects (since iterators of
Collections.synchronizedMapare not synchronized). - Contract of
Iteratorwould be broken - you may getNoSuchElementExceptionwhen callingnext()afterhasNext()returnedtrue.
加载中,请稍侯......
精彩评论