!7
static int n = 1000000;
// iterate safely (& quickly) in the face of concurrent modifications
static Iterator iterateKeysQuickly(final NavigableMap map) {
ret iteratorFromFunction(new F0() {
Iterator it = keys(map).iterator();
A key;
A get() {
synchronized(map) {
try {
ret key = it.next();
} catch (ConcurrentModificationException e) {
it = map.tailMap(key, false).keySet().iterator();
ret key = it.next(); // Can't throw another exception
}
}
}
});
}
p {
SortedMap map = synchroSortedMap(litcimap());
repeat n {
map.put(randomID(), Bool.TRUE);
}
repeat 5 {
int i = 0;
long sum = 0;
time "Iterating" {
for (S key : keys(map)) {
++i;
sum += key.hashCode();
}
}
assertEquals(i, n);
i = 1;
long sum2 = 0;
time "Iterating quickly" {
for (S key : iterateKeysQuickly(map)) {
++i;
sum += key.hashCode();
}
}
assertEquals(i, n);
assertEquals(sum, sum2);
}
}