I played around with java.util.HashMap
to learn what the fail-fast
behaviour is.
HashMap map = new HashMap();
map.put("jon", 10);
map.put("sean", 11);
map.put("jim", 12);
map.put("stark", 13);
map.put("vic", 14);
Set keys = map.keySet();
for(Object k:keys) {
System.out.println(map.get(k));
}
for(Object k:keys) {
String key =(String)k;
if(key.equals("stark")) {
map.remove(key);
}
}
System.out.println("after modifn");
for(Object k:keys) {
System.out.println(map.get(k));
}
I got the result
12
11
10
14
13
after modifn
12
11
10
14
I also tried using an iterator
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(key.equals("stark")) {
map.remove(key);
}
}
I didn't get any ConcurrentModificationException
in either case ..Is this because (from javadoc)
the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis
I checked another thread which says ,it WILL throw ConcurrentModificationException
..what do you think?
That aside, essentially, "fail-fast" in this sense means that an Iterator over a HashMap will throw an exception if it detects that another thread has modified the targeted HashMap - if you look in the source for HashMap, you will see this is done by simply checking a counter for the number of expected modifications.
Structural modification means adding, removing any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator. Fail-Safe iterators don't throw any exceptions if a collection is structurally modified while iterating over it.
Iterator of ConcurrentHashMap is fail-safe, it means that it doesn't throw ConcurrentModificationException even if underlying ConcurrentHashMap is modified once Iteration begins.
The Fail fast iterator aborts the operation as soon it exposes failures and stops the entire operation. Comparatively, Fail Safe iterator doesn't abort the operation in case of a failure. Instead, it tries to avoid failures as much as possible.
Given the output that you have shown:
12
11
10
14
13 // notice this?
after modifn
12
11
10
14
Since 13 is the last key-value pair, when you Iterate
through your HashMap
and then finally remove the key-value corresponding to stark 13
, that stops the Iteration
just after the HashMap
has been modified, hence, it doesn't iterate
anymore. So no ConcurrentModificationException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With