LoginSignup
4
5

More than 5 years have passed since last update.

try-with-resourcesのclose時にflushは走るのか?

Last updated at Posted at 2015-06-29

はじめに

Java7.0から導入されたtry-with-resources構文
自動でcloseされるので便利ですが、Bufferedxxx系のflush処理も動作するのか心配だったので確認しました

結論

標準APIではflushしてそう
ただし保証されているものではなく実装による(大概は大丈夫だと思うのですが…)

調査内容

以下の様なコードを組んで単純に実行してみました
close,fluseをオーバーライドしてコメントを出力しただけですね
※try-with-resourcesでdispose時に実行されるのはcloseメソッドとなります

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

import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;

public class CustomBufferedOutputStream extends BufferedOutputStream {

  public CustomBufferedOutputStream(OutputStream out) {
    super(out);
  }

  @Override
  public void flush() throws IOException{
    System.out.println("OUTPUT flush executed!!");
    super.flush();
  }

  @Override
  public void close() throws IOException {
    System.out.println("OUTPUT close executed!!");
    super.close();
  }
}
main.java
package jp.co.test.autocloseable;

import java.io.FileOutputStream;
import java.io.IOException;

public class main {
  public static void main(String[] args) throws IOException {
    try (
      FileOutputStream outFile = new FileOutputStream("xyz.bin");
      CustomBufferedOutputStream outBuffer = new CustomBufferedOutputStream(outFile);
    ){
      outBuffer.write(Byte.parseByte("1"));
      outBuffer.write(Byte.parseByte("2"));
    } 
  }
}

この結果、以下の様な標準出力が表示されます

標準出力
OUTPUT close executed!!
OUTPUT flush executed!!

flushは実行されてますね!
closeが先に実行されてますが、これはオーバーライドして標準出力しているからですね
下記にOpenJDKのコードを示しましたがちゃんとflush→closeの順に処理してます

FilterOutputStream.java
public void  close() throws IOException {
  try {
    flush();
  } catch (IOException ignored) {
  }
  out.close();
}

というわけで問題ないようです
ただ当たり前ですが、これは保証されているわけではなく実装によるところが大きいので念のため気をつけてください

4
5
1

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
4
5