ARM Blocks: ease of use and for loops

Howard Lovatt howard.lovatt at
Wed Oct 21 05:15:22 PDT 2009


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 { @Override void close();

interface SafeCloseableIterable<E> extends Iterable<E> { @Override public
SafeCloseableIterator<E> iterator(); }

interface SafeCloseableIterator<E> extends SafeCloseable, Iterator<E> {}

in package;

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

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 is part of the new hierarchy for
backward compatibility and also to allow SafeCloseable's to be passed in
where'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

Do others think these interfaces and the for loop suggestion useful/viable?

 -- Howard.

More information about the coin-dev mailing list