JDK-6179333 : Allow guaranteed disposing of iterators in enhanced for loop
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2004-10-14
  • Updated: 2011-10-31
  • Resolved: 2011-10-31
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
Guarantee that if iterator class implements java.io.Closeable (or some newly introduced interface), close() will be called after termination of iteration, regardless of whether we terminate normally or through exception.

JUSTIFICATION :
With the advent of enhanced for loop, one could write code like:

  for (String line : new IterableFile("foo.txt")) {
      // process line
  }

The problem is that, care must be taken in the implementation of Iterator to close the file immediately upon any exception. Moreover, it is impossible to close the file properly if the processing block of the for loop throws an exception.


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
for (Type t : iterable) {
    ...
}

should be equal to

Iterator<T> it = iterable.iterator();
try {
    while (it.hasNext()) {
        Type t = it.next();
        ....
    }
} finally {
    if (it instanceof Closeable) {
        ((Closeable) it).close();
    }
}
###@###.### 10/14/04 19:11 GMT

Comments
EVALUATION Proposals for new features in the Java programming language are no longer being accepted or maintained in the bug database at http://bugs.sun.com/. This also applies to proposals for new features in the Java Virtual Machine (that is, in the abstract JVM, as opposed to a JVM implementation like HotSpot). All proposals for new features should be made through the "JDK Enhancement - Proposal & Roadmap Process" described at http://openjdk.java.net/jeps/1. Consequently, this specific request to change the Java programming language will not be considered further. The bug database continues to accept and maintain submissions about technical errors in the design and specification of the Java programming language and the Java Virtual Machine.
20-11-2006