Skip to content

Instantly share code, notes, and snippets.

@developer-sdk
Created March 6, 2018 13:27
Show Gist options
  • Select an option

  • Save developer-sdk/913b9ee0999b93503f8e6b9d5a4d8fbb to your computer and use it in GitHub Desktop.

Select an option

Save developer-sdk/913b9ee0999b93503f8e6b9d5a4d8fbb to your computer and use it in GitHub Desktop.
java iterator Fail-Safe vs Fail-Fast
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
public class IteratorFailFastAndFailSafe {
public static void funcFailFast() {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
Integer number = iterator.next();
numbers.add(50);
System.out.println(number);
}
}
public static void funcFailSafe() {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("First", 10);
map.put("Second", 20);
map.put("Third", 30);
map.put("Fourth", 40);
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
map.put(key, 50);
}
}
public static void main(String[] args) {
funcFailFast();
funcFailSafe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment