Question Edited :
HashSet and HashMap are fail-fast(but that is not gauranteed) as mentioned in code :
void goHashSet() {
Set set = new HashSet();
for (int i = 1; i <= 10; i++) {
set.add(i);
}
Iterator i = set.iterator();
while (i.hasNext()) {
// set.add(16);//Exception in thread "main"
// java.util.ConcurrentModificationException
System.out.println("HashSet >>> itertor >>>" + i.next());
}
}
Now, i want the example and the collections which are fail-safe
as much as i know: ConcurrentHashMap,CopyOnWriteArrayList are fail-safe..but how to code it to show that they are fail-safe
Edit and Undestanding of what I want and how I achieved it :
if we use HashMap
void goHashMap() {
Map mp = new HashMap();
for (int i = 19; i <= 24; i++) {
mp.put(i, "x");
}
Set setKeys = mp.keySet();
Iterator i = setKeys.iterator();
while (i.hasNext()) {
// mp.put(499, "x");// Exception in thread "main"
// java.util.ConcurrentModificationException
System.out.println("HashMap >>> itertor >>>" + i.next());
}
}
we get ConcurrentMException
but the same code is done with ConcurrentHashMap, no error is there (non-multithreading enviro)
void goConcurrentHashMap() {
Map mp = new ConcurrentHashMap();
for (int i = 19; i <= 24; i++) {
mp.put(i, "x");
}
Set setKeys = mp.keySet();
Iterator i = setKeys.iterator();
while (i.hasNext()) {
mp.put(499, "x");
System.out.println("HashConcurrentMap >>> itertor >>>" + i.next());
}
}
whats more : in multithreading enviro the ConcurrentHashmap might get fail-fast and throw exception CME
The API Javadoc (both for
HashSetandHashMap) only makes a soft guarantee to fail-safety:The identical behaviour is explained by the fact that
HashSetis implemented on top of aHashMapinternally.Feel free to check out the source code, bundled with your JDK installation though.
Update
Have a look at the collections in the
java.util.concurrentpackage.The nature of concurrency is such that it is impossible to prove thread-safety (or fail-safety) by tests alone. You can only prove the opposite, i.e. that a specific class is not thread-safe (if that happens to be the case). This is exactly what makes concurrency hard.
The closest to proving such things is thorough analysis of the code in question by one or more concurrency experts. Some static analysis tools can spot some issues too, but again, a clean static analysis result is no guarantee.