Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to add elements to a SortedSet while iterating

Tags:

java

sortedset

Is it safe to add elements to a modifiable SortedSet while iterating over that set? In particular, is it safe to add elements to later in the set than the element indicated by the iterator?

For example, will the following code corrupt the SortedSet s or throw an exception (which would likely to be a ConcurrentModificationException):

 /**
  * s not null, is modifiable.
  */
 private final addSelectedFollowers(final SortedSet<Integer> s)
 {
    for (Integer i: s) {
       if (shouldAddNext(i)) {
          s.add(i + 1);
       }
    }
 }

 protected abstract boolean shouldAddNext(int i);

My guess is that it is safe, but I can't find a clear statement in the JRE API documentation. I know that if the behaviour is not specified, the implementation is free to decide upon the behaviour. Lack of an explicit statement in the documentation of SortedSet is not enough to answer the question one way or the other; the required behaviour might be specified indirectly, in the documentation for a different class or interface. The JRE documenters unfortunately do not always explicitly state what is permitted. I'm therefore looking for answers that reference the JRE API, rather than a bald assertion of yes or no. I also know that a SortedSet can be made unmodifiable, which would make the SortedSet.add() fail; I'm interested in the case of a modifiable SortedSet.

Note that I'm asking about adding elements to the set, not modifying elements within the set.

like image 672
Raedwald Avatar asked Dec 19 '22 19:12

Raedwald


1 Answers

It depends on the implementation. For example in case of TreeSet, iterators are fail-fast, therefore adding elements while iterating will trigger a ConcurrentModificationException.

From the JavaDoc of TreeSet:

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.

Other implementations with non-fail-fast iterators may allow adding elements while iterating.

like image 162
janos Avatar answered Dec 21 '22 11:12

janos