Which line of code, when inserted at //INSERT CODE HERE, will ensure that on execution, single or multiple MyColors
instances won't throw a ConcurrentModificationException at runtime?.
class MyColors extends Thread{ static private Map<Integer, String> map; MyColors() {/* w ww. j ava 2s . c om*/ //INSERT CODE HERE map.put(1, "red"); map.put(2, "blue"); map.put(3, "yellow"); } public void iterate() { Iterator iter = map.keySet().iterator(); while(iter.hasNext()) { Integer key = (Integer)iter.next(); String val = (String)map.get(key); System.out.println(key + "-" + val); add(4, "green"); } } public void add(Integer i, String v){ map.put(i, v); } public void run() { iterate(); } }
a map = new HashMap<Integer, String>(); b map = new NoExceptionHashMap<Integer, String>(); c map = new ConcurrentMap<Integer, String>(); d map = new ConcurrentHashMap<Integer, String>(); e map = new CopyOnWriteHashMap<Integer, String>(); f None of the above
d
Option (a) is incorrect because iterators returned by HashMap are fail-fast.
If a collection changes (addition, deletion, or modification of elements) after you retrieved an iterator, it will throw a ConcurrentModificationException.
Options (b) and (e) are incorrect because these use invalid class names.
Option (c) is incorrect because ConcurrentMap is an interface; therefore, it can't be instantiated.
Option (d) is correct because iterators returned by ConcurrentHashMap are fail-safe.
If a collection changes (elements are added, deleted, or modified) after the iterator is created, they don't throw any runtime exception.
These iterators work with a clone of the collection rather than working with the collection itself.