Here is a quick tip for time constrained operations in java. If you need to process a long list but stop at some point in time, here is a solution:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class TimedIterator<T> implements Iterator<T> {
private Iterator<T> originalIterator;
protected boolean nowIsTheTime;
private final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
TimedIterator.this.nowIsTheTime = true;
}
};
public TimedIterator(Iterator<T> originalIterator, long duration, TimeUnit units) {
this.originalIterator = originalIterator;
Timer timer = new Timer();
timer.schedule(this.timerTask, units.toMillis(duration));
}
@Override
public boolean hasNext() {
return this.originalIterator.hasNext() && !this.nowIsTheTime;
}
@Override
public T next() {
if (this.nowIsTheTime) {
throw new NoSuchElementException();
}
return this.originalIterator.next();
}
}
To use it, you can do something like this:
TimedIterator<Integer> it = new TimedIterator<>(testIterator, 1, TimeUnit.SECONDS);
where testIterator
is an instance of any iterator implementing class.
This can also be used for streams:
Stream<Integer> stream = StreamSupport
.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false);