如果我想要达到以下目标,则我会使用<代码>目前HashMap。
- 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.
有时,我使用<代码>enum <>/code>作为关键,从,EnumMap Javadoc ,我认识到,
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.
因此,替换我是安全的。
Map<Country, String> map = new ConcurrentHashMap<Country, String>();
with
Map<Country, String> map = Collections.synchronizedMap(new EnumMap<Country, String>(Country.class));
我知道putIfAbsent
in EnumMap
,但此时此刻,我不要求这样做。