Skip to content

Instantly share code, notes, and snippets.

@HenryLoenwind
Last active December 22, 2016 19:40
Show Gist options
  • Save HenryLoenwind/237339d95470d7b283edb895d4fba6b3 to your computer and use it in GitHub Desktop.
Save HenryLoenwind/237339d95470d7b283edb895d4fba6b3 to your computer and use it in GitHub Desktop.
package test;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class ConcurrentIterator<E> implements Iterator<E> {
private final Iterable<E> iterable;
private Iterator<E> iterator;
private Set<E> seen = null;
private List<E> seenList;
private E next = null;
public ConcurrentIterator(Iterable<E> iterable) {
this.iterable = iterable;
this.iterator = iterable.iterator();
this.seenList = new ArrayList<E>(); // TODO second constructor that takes a Collection to init the size here
}
@Override
public boolean hasNext() {
while (true) {
try {
while (iterator.hasNext()) {
next = iterator.next();
if (seen == null) {
seenList.add(next);
return true;
} else if (!seen.contains(next)) {
seen.add(next);
return true;
}
}
return false;
} catch (ConcurrentModificationException e) {
iterator = iterable.iterator();
if (seen == null) {
seen = new HashSet<E>(seenList);
seenList = null;
}
}
}
}
@Override
public E next() {
return next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment