Videos
Create a custom iterator which implement the AutoCloseable interface
public interface CloseableIterator<T> extends Iterator<T>, AutoCloseable {
}
And then use this iterator in a try with resource statement.
try(CloseableIterator iterator = dao.findAll()) {
while(iterator.hasNext()){
process(iterator.next());
}
}
This pattern will close the underlying resource whatever happens: - after the statement complete - and even if an exception is thrown
Finally, clearly document how this iterator must be used.
If you do not want to delegate the close calls, use a push strategy. eg. with java 8 lambda:
dao.findAll(r -> process(r));
In your implementation you could close it your self, if when the iteratoror is exhausted.
public boolean hasNext() {
....
if( !hasNext ) {
this.close();
}
return hasNext;
}
And clearly document:
This iterator will invoke close() when hasNext() return false, if you need to dispose the iterator before make sure you call close your self
example:
void testIt() {
Iterator i = DbIterator.connect("db.config.info.here");
try {
while( i.hasNext() {
process( i.next() );
}
} finally {
if( i != null ) {
i.close();
}
}
}
Btw, you could while you're there you could implement Iterable and use the enhanced for loop.