Java7のAutoCloseable

Java5 から Closeable が実装されていました。

A Closeable is a source or destination of data that can be closed. The close method is invoked to release resources that the object is holding (such as open files).

Closeableは、閉じることことのできる入力または出力データです。closeメソッドは、オブジェクトが保持しているリソース(開いているファイルなど)を解放するために呼び出されます。

http://download.java.net/jdk7/docs/api/java/io/Closeable.html
void close() throws IOException;

使用例:Closeable インターフェースを使ってあげて - A Memorandum
(ちなみに、自分は NicoCache のソースを見ていて知りました…)


これが、Java7 では進化して AutoCloseable なるものが追加されるそうです。

A resource that must be closed when it is no longer needed.


void close() throws Exception
Close this resource, relinquishing any underlying resources. This method is invoked automatically by the try-with-resources statement.

Classes implementing this method are strongly encouraged to be declared to throw more specific exceptions (or no exception at all, if the close cannot fail).

Note that unlike the close method of Closeable, this close method is not required to be idempotent. In other words, calling this close method more than once may have some visible side effect, unlike Closeable.close which is required to have no effect if called more than once.

              • -

必要がなくなったときに、リソースを必ず閉じます。


元になるリソースを放棄すると、このリソースを閉じます。このメソッドは、try-with-resourcesで自動的に呼び出されます。

このメソッドを実装するクラスは、より詳細な例外を宣言することを強く推奨します。(もしくは、閉じるのが失敗しないようまったく例外を出さない)。

メモ:
Closeableのcloseメソッドとは異なり、このcloseメソッドが冪等(何度呼んでも同じ結果)である必要はないことに注意してください。言い換えれば、複数回呼ばれても影響がないようにする必要のあるCloseable.closeとは違って、いくつかの目に見える副作用があるかもしれません

http://download.java.net/jdk7/docs/api/java/lang/AutoCloseable.html

*1


「try-with-resources」は、Java7の新文法です。
ようするに、C# の using みたいです。

try (
  FileInputStream in = new FileInputStream("xanadu.txt");
  FileOutputStream out = new FileOutputStream("outagain.txt")
) {
  int c;
  while((c=in.read()) != -1 )
    out.write();
}

Java の自動リソース管理より


たぶん確定なのかな・・・?
ちなみに、Java7自体は2011年中期にリリース予定とのこと*2
http://journal.mycom.co.jp/news/2010/10/12/039/index.html


Javaは、新しい機能を使いたがらない保守的な人(?)が多いような気がするので、実際に使えるのはまだ先かもしれません。
早く使えるようにならないかな…。

*1:翻訳はGoogle翻訳の力を借りてます。。。

*2:数年前から「あと半年後」と言われ続けているので、本当かどうかわからないですが…