ARM Blocks: ease of use and for loops

Neal Gafter neal at gafter.com
Wed Oct 21 08:08:16 PDT 2009


I definitely agree that the semantics of the foreach loop should be modified
to take closability of the iterator into account, but I think it would be
more in the spirit of the existing ARM proposal to do this without adding a
bunch of new interfaces.  For example, one approach would be: in a foreach
loop over a collection expression e, if the type of e.iterator() extends
Closeable, then it is automatically closed when the loop exits.

On Wed, Oct 21, 2009 at 5:15 AM, Howard Lovatt <howard.lovatt at iee.org>wrote:

> Hi,
>
> I have been experimenting in my own code with various 'manual' versions of
> ARM blocks and have found the following interfaces to be useful:
>
>
> in package java.util;
>
> interface Closeable { void close() throws Exception; }
>
> interface CloseableIterable<E> extends Iterable<E> { @Override public
> CloseableIterator<E> iterator(); }
>
> interface CloseableIterator<E> extends Closeable, Iterator<E> {}
>
> interface SafeCloseable extends java.io.Closeable { @Override void close();
> }
>
> interface SafeCloseableIterable<E> extends Iterable<E> { @Override public
> SafeCloseableIterator<E> iterator(); }
>
> interface SafeCloseableIterator<E> extends SafeCloseable, Iterator<E> {}
>
>
> in package java.io;
>
> interface Closeable extends java.util.Closeable { @Override void close()
> throws IOException; }
>
>
> The purpose of the interfaces CloseableIterable and CloseableIterator are
> to
> enable for loops to close resources automatically. A for loop whose
> iteratable is of type CloseableIterable, e.g.:
>
> for ( final E e : closeableIterable ) { ... }
>
> is expanded, using the new ARM block, to:
>
> try ( final CloseableIterator<E> i = closableIterable.iterator() ) {
>  while ( i.hasNext() ) {
>    final E e = i.next();
>    ...
>  }
> }
>
> The semantics of a closed iterator is that hasNext returns false and next
> throws a NoSuchElementException. The purpose of the Safe versions is to
> simplify coding in the, common in my code, cases when close doesn't throw
> an
> exception. Also note that java.io.Closeable is part of the new hierarchy
> for
> backward compatibility and also to allow SafeCloseable's to be passed in
> where java.io.Closeable's are expected. The ARM block only has to deal with
> java.util.Closeable, but the for expansion must get the types more exact
> (for expansion already deals with arrays and Iterables so hopefully adding
> CloseableIterable and SafeCloseableIterable won't be too hard).
>
> I have tried trawling the coin archives and I can't find a suggestion
> identical to this (though there are suggestions along these lines), so
> hopefully I haven't missed something in the archive and this is a new
> contribution.
>
> Do others think these interfaces and the for loop suggestion useful/viable?
>
>  -- Howard.
>
>



More information about the coin-dev mailing list