Closing a java.util.Iterator

前端 未结 7 1818
清酒与你
清酒与你 2020-12-29 02:32

I\'ve implemented a custom java.util.Iterator using a resource that should be released at the end using a close() method. That resource could

7条回答
  •  孤独总比滥情好
    2020-12-29 03:09

    Create a custom iterator which implement the AutoCloseable interface

    public interface CloseableIterator extends Iterator, 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));
    

提交回复
热议问题