2012年2月20日月曜日

[Java7][検証]try-with-resourcesで複数リソースを登録した際のclose呼び出しの順序について

以前にご紹介したJava7の新機能であるtry-with-resourcesですが
複数リソースを登録した場合のcloseメソッドの呼び出し順序って
どうなるの?という質問を頂きましたので検証してみました。


今回は以下の様な独自実装のresourceクラスを4つ作成しました。

TestResource1.java
public class TestResource1 implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("TestResource1 Call close Method");
    }

    @Override
    public String toString() {
        return "TestResource [getClass()=" + getClass() + ", hashCode()="
                + hashCode() + ", toString()=" + super.toString() + "]";
    }
}
※上記と同様の実装で2~4は実装しています。


Main.java
public class Main {
    public static void main(String[] args) {
        try (AutoCloseable imp1 = new TestResource1();
             AutoCloseable imp2 = new TestResource2();
             AutoCloseable imp3 = new TestResource3();
             AutoCloseable imp4 = new TestResource4();) {
            System.out.println(imp1);
            System.out.println(imp2);
            System.out.println(imp3);
            System.out.println(imp4);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("main側のcache句");
        }
    }
}

実行結果は以下の通り

// 実行結果
TestResource [getClass()=class com.oracle.test.TestResource1, hashCode()=19272103, toString()=com.oracle.test.TestResource1@12611a7]
TestResource [getClass()=class com.oracle.test.TestResource2, hashCode()=5309741, toString()=com.oracle.test.TestResource2@51052d]
TestResource [getClass()=class com.oracle.test.TestResource3, hashCode()=19583390, toString()=com.oracle.test.TestResource3@12ad19e]
TestResource [getClass()=class com.oracle.test.TestResource4, hashCode()=2628939, toString()=com.oracle.test.TestResource4@281d4b]
TestResource4 Call close Method
TestResource3 Call close Method
TestResource2 Call close Method
TestResource1 Call close Method

検証する前はもしかしたらそれぞれが別Theare上で並列でcloseが呼び出されて
順番が入れ替わるのかも!?とか想像していましたが、どうも単純に最後に登録した物から
順番にcloseメソッドが呼ばれている様子ですね。

Eclipseのデバッカ等でステップ実行した場合でもTestResource4のcloseメソッド内で
breakした場合はその後のcloseが呼ばれませんでした。

closeの呼ばれる順番を考慮する必要がある場合は一番最後にcloseしたいものから
順番に登録すればよさそうですね。

0 件のコメント:

コメントを投稿