Closing a java.util.Iterator

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));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)