Created
March 6, 2018 13:27
-
-
Save developer-sdk/913b9ee0999b93503f8e6b9d5a4d8fbb to your computer and use it in GitHub Desktop.
java iterator Fail-Safe vs Fail-Fast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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