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 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:
Collections.synchronizedMapare not synchronized).Iteratorwould be broken – you may getNoSuchElementExceptionwhen callingnext()afterhasNext()returnedtrue.