Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8251942

PrintStream specification is not clear which flush method is automatically invoked

XMLWordPrintable

    • b15

      Class-level spec https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/io/PrintStream.html#writeBytes(byte%5B%5D) as well as specification for various writeX methods have the following assertions:

      "a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written"
      "If automatic flushing is enabled then the flush method will be invoked"

      It looks like PrintStream::flush is expected to be called, however the OpenJDK implementation calls ::flush method directly on the wrapped OutputStream.

      Consider the following code:

              new PrintStream(new OutputStream() {
                  @Override
                  public void write(int b) throws IOException {
                      System.out.println("OutputStream::write");
                  }
                  @Override
                  public void flush() throws IOException {
                      System.out.println("OutputStream::flush");
                  }
              }, /*autoFlush:*/ true) {
                      @Override
                      public void flush() {
                          System.out.println("PrintStream::flush");
                          super.flush();
                      }
              }.write(new byte[]{0, 1, 2});

      For OpenJDK the output would be:

      OutputStream::write
      OutputStream::write
      OutputStream::write
      OutputStream::flush

            bpb Brian Burkhalter
            dbessono Dmitry Bessonov
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:
              Resolved: