LoginSignup
3
2

More than 5 years have passed since last update.

try-with-resources時のclose順について

Last updated at Posted at 2015-06-29

はじめに

try-with-resourcesは自動でcloseしてくれる便利な構文です
ただ以下の様な順でインスタンス化したものをcloseする際には順序を逆にしなければいけないですよね
これが正しい順番になるかを検証してみました

(e.g)
1. Aをインスタンス化
2. インスタンスAを用いてBをインスタンス化
→→→→→ これをcloseする際にはB→Aの順でcloseしてほしい

結論

ただしくB→Aの順でcloseされる

調査内容

TestCloseableA.java
package jp.co.test.autocloseable;

public class TestCloseableA implements AutoCloseable {

  public TestCloseableA(){
    System.out.println("Aのコンストラクタだよ");
  }

  @Override
  public void close() throws Exception {
    System.out.println("AのCloseだよ");
  }
}
TestCloseableB.java
package jp.co.test.autocloseable;

public class TestCloseableB implements AutoCloseable {

  public TestCloseableB() {
    System.out.println("Bのコンストラクタだよ");
  }

  @Override
  public void close() throws Exception {
    System.out.println("BのCloseだよ");
  }
}
main.java
package jp.co.test.autocloseable;

public class TestCloseableA {
  public static void main(String[] args) {

    try(TestCloseableA a = new TestCloseableA();
        TestCloseableB b = new TestCloseableB();) {
      System.out.println("Try処理開始");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
標準出力
Aのコンストラクタだよ
Bのコンストラクタだよ
Try処理開始
BのCloseだよ
AのCloseだよ

問題なく逆になってますね 想定どおりです

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2