Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a java.util.Iterator

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 be a java.sql.ResultSet, a java.io.InputStream etc...

public interface CloseableIterator<T> extends Iterator<T>   {   public void close();   } 

Some external libraries using this iterator might not know that it must be closed. e.g:

public boolean isEmpty(Iterable<T> myiterable)  {  return myiterable.iterator().hasNext();  } 

In that case, is there a way to close this iterator?

Update: many thanks for the current answers . I'll give a (+1) to everybody. I do already close the Iterator when hasNext() returns false. My problem is when the loop iterating breaks before the last iteration as it is shown in my example.

like image 951
Pierre Avatar asked Jul 15 '10 16:07

Pierre


People also ask

How do I close an iterator?

You extend Iterator and AutoCloseable interfaces, implement the Close method and use the Iterator in a try-with-resources. The Runtime will call close for you once the Iterator is out of scope.

What is Java Util iterator?

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping. To use an Iterator, you must import it from the java. util package.

What does remove in an iterator do?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.

How does Java iterator work?

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. Before you can access a collection through an iterator, you must obtain one.


1 Answers

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)); 
like image 172
Nicolas Labrot Avatar answered Sep 25 '22 16:09

Nicolas Labrot