-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterators
50 lines (44 loc) · 2.22 KB
/
iterators
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
----------------------
| fail fast iterator |
----------------------
* The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
* Note that 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. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
* wird über ein internes status feld realisiert, bspw ArrayList mit int modCount
void failFastIterator() {
List<String> l = new ArrayList<>();
l.add("a");
for (String s : l) { // ConcurrentModificationException beim zweiten Aufruf
l.add(s);
}
}
----------------------
| fail safe iterator |
----------------------
* es fliegt keine exception
* iteratoren arbeiten auf einer kopie
* diese kopie muss nicht aktuell sein
klappt: gibt [a,a] aus
void failSafeIterator() {
List<String> l = new CopyOnWriteArrayList<>();
l.add("a");
for (String s : l) {
l.add(s);
}
System.out.println(l);
}
------------------------------
| weakly consistent iterator |
------------------------------
Iterators returned by the collection views are weakly consistent:
they will never throw ConcurrentModificationException
and they may or may not show the effects of any modifications to the map
that occur while the iteration is in progress.
funktioniert, ausgabe [a, aa]
void weaklyConsistentIterator() {
ConcurrentSkipListSet<String> set = new ConcurrentSkipListSet<>();
set.add("a");
for (String s : set) {
set.add(s + s);
}
System.out.println(set);
}