I repeat Iteratorwhere it hasNext()never returns false. However, after a certain time (say 20 seconds), I want to stop the iteration. The problem is that the method is next() Iteratorblocked, but even then, after a certain time, I just need the iteration to stop.
Here is my example Iterableand Iteratorto simulate my problem.
public class EndlessIterable implements Iterable<String> {
static class EndlessIterator implements Iterator<String> {
public boolean hasNext() { return true; }
public String next() {
return "" + System.currentTimeMillis();
}
}
public Iterator<String> iterator() { return new EndlessIterator(); }
}
Here is my code for testing.
EndlessIterable iterable = new EndlessIterable();
for(String s : iterable) { System.out.println(s); }
I wanted to put the code / logic into the class Iterableto be created Timer, so after the specified time has passed, the exception will be chosen so as to stop the iteration.
public class EndlessIterable implements Iterable<String> {
static class EndlessIterator implements Iterator<String> {
public boolean hasNext() { return true; }
public String next() {
try { Thread.sleep(2000); } catch(Exception) { }
return "" + System.currentTimeMillis();
}
}
static class ThrowableTimerTask extends TimerTask {
private Timer timer;
public ThrowableTimerTask(Timer timer) { this.timer = timer; }
public void run() {
this.timer.cancel();
throw new RuntimeException("out of time!");
}
}
private Timer timer;
private long maxTime = 20000;
public EndlessIterable(long maxTime) {
this.maxTime = maxTime;
this.timer = new Timer(true);
}
public Iterator<String> iterator() {
this.timer.schedule(new ThrowableTimerTask(this.timer), maxTime, maxTime);
return new EndlessIterator();
}
}
Then I will try to check this code as follows.
EndlessIterable iterable = new EndlessIterable(5000);
try {
for(String s : iterable) { System.out.println(s); }
} catch(Exception) {
System.out.println("exception detected: " + e.getMessage());
}
System.out.println("done");
, , , RuntimeException , ,
, , ?
: