为什么PrintStream.close()最终会被调用两次?

时间:2009-05-12 13:36:14

标签: java inheritance printstream

令我惊讶的是,下面的代码打印出两次“关闭”。通过调试器,似乎MyPrintStream.close()调用super.close(),最终再次调用MyPrintStream.close()

    
import java.io.*;

public class PrintTest
{
    static class MyPrintStream extends PrintStream
    {
        MyPrintStream(OutputStream os)
        {
            super(os);
        }

        @Override
        public void close()
        {
            System.out.println("Close");
            super.close();
        }
    }

    public static void main(String[] args) throws IOException
    {
        PrintStream ps = new MyPrintStream(new FileOutputStream(File.createTempFile("temp", "file")));
        ps.println("Hello");
        ps.close();
    }
}

为什么会这样?我不应该扩展PrintStream吗?

2 个答案:

答案 0 :(得分:11)

如果您在调试器中查看代码并在close()方法中设置断点,它将显示正在调用您的close()方法的堆栈跟踪:

  1. 您的主要方法
  2. sun.nio.cs.StreamEncoder $ CharsetSE.implClose()第431行
  3. 后者的完整堆栈跟踪如下所示:

    PrintTest$MyPrintStream.close() line: 20    
    sun.nio.cs.StreamEncoder$CharsetSE.implClose() line: 431 [local variables unavailable]  
    sun.nio.cs.StreamEncoder$CharsetSE(sun.nio.cs.StreamEncoder).close() line: 160 [local variables unavailable]    
    java.io.OutputStreamWriter.close() line: 222 [local variables unavailable]  
    java.io.BufferedWriter.close() line: 250 [local variables unavailable]  
    PrintTest$MyPrintStream(java.io.PrintStream).close() line: 307  
    PrintTest$MyPrintStream.close() line: 20    
    PrintTest.main(java.lang.String[]) line: 27 
    

    遗憾的是,我无法告诉为什么 StreamEncoder会回调到你的PrintStream,因为我的IDE没有sun.nio.cs.StreamEncoder的源附件:(这是JDK 6顺便说一句,如果那很重要。

    顺便提一下,如果您提出这个问题,因为您发现close()方法中的自定义代码运行了两次,那么您应该检查是否this.closingPrintStream.close()将此设置为true(并且类的注释状态为/* To avoid recursive closing */)。

答案 1 :(得分:1)

看一下PrintStream的来源。

它有两个对基础Writer textOutcharOut的引用,一个基于字符,一个基于文本(无论这意味着什么)。此外,它继承了对基于字节的OutputStream的第三个引用,称为out

/**
 * Track both the text- and character-output streams, so that their buffers
 * can be flushed without flushing the entire stream.
 */
private BufferedWriter textOut;
private OutputStreamWriter charOut;

close()方法中,它会关闭所有这些内容(textOutcharOut基本相同)。

 private boolean closing = false; /* To avoid recursive closing */

/**
 * Close the stream.  This is done by flushing the stream and then closing
 * the underlying output stream.
 *
 * @see        java.io.OutputStream#close()
 */
public void close() {
synchronized (this) {
    if (! closing) {
    closing = true;
    try {
        textOut.close();
        out.close();
    }
    catch (IOException x) {
        trouble = true;
    }
    textOut = null;
    charOut = null;
    out = null;
    }
}
}

现在,有趣的是charOut包含一个(包装的)引用PrintStream本身(注意构造函数中的init(new OutputStreamWriter(this))

private void init(OutputStreamWriter osw) {
   this.charOut = osw;
   this.textOut = new BufferedWriter(osw);
}

/**
 * Create a new print stream.
 *
 * @param  out        The output stream to which values and objects will be
 *                    printed
 * @param  autoFlush  A boolean; if true, the output buffer will be flushed
 *                    whenever a byte array is written, one of the
 *                    <code>println</code> methods is invoked, or a newline
 *                    character or byte (<code>'\n'</code>) is written
 *
 * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
 */
public PrintStream(OutputStream out, boolean autoFlush) {
this(autoFlush, out);
init(new OutputStreamWriter(this));
}

因此,对close()的调用将调用charOut.close(),而close()又会再次调用原始{{1}},这就是为什么我们使用结束标志来缩短无限递归。< / p>