Iteration Interruption の処理

IEnumerator<T> を実装していれば必ず IDisposable である理由」は興味深かった。Java では Iterable / Closable がありますが、どうなんだろうと思ったら次のようなバグレポートを見つけました。


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.

Mustang にはまだパッチが入っていないってことですかね。うーむ。それにしても、Closable というインターフェイスは微妙と思うんですよ。javax.imageio.ImageWriter#dispose() のように dispose() という名前を採用しているクラスが結構あるし。CORBA 系なら destroy() か…。渋々Disposable属性としてメソッド名も合わせて格納するのがよかったんじゃないかと思います (パフォーマンスの問題があるのかな)。

そういえば PHP でも SPL というのがあるけど、こういう tweaks は実装しておいた方がいいですよね (たとえ参照カウントベースの GC でもね)。提案しようかな。