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

Add OutputStream.write(ByteBuffer)

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs
    • None

      Adding OutputStream.write(ByteBuffer) could improve the following cases:

      a) OpenJDK's implementations of InputStream.transferTo(OutputStream) have to copy the buffers, as passing byte arrays to untrusted OutputStream implementations can create security issues: https://github.com/openjdk/jdk/pull/16879 , https://github.com/openjdk/jdk/pull/16893

      b) Channels.newChannel(outputStream) has to copy the data, however, it could pass the incoming ByteBuffer without copies: https://github.com/openjdk/jdk/blob/d23f4f12adf1ea26b8c340efe2c3854e50b68301/src/java.base/share/classes/java/nio/channels/Channels.java#L390

      c) Passing naked byte[] to untrusted OutputStream implementations is not secure, so moving to ByteBuffer API + read-only byte buffers should improve the security.

      ----

      ByteBuffer has .asReadOnlyBuffer(), and it should be reasonably safe to pass read-only byte buffers without copying them, so if OutputStream.write(ByteBuffer) was there, then implementation of ByteArrayInputStream.transferTo could be improved as out.write(ByteBuffer.wrap(buf, ...));

      It would avoid copying the data, and it might enable more efficient implementation when sending the data to a file or network.

      The default implementation of OutputStream.write(ByteBuffer buffer) could be something like if (buffer.hasArray()) { write(buffer.array(), ...); } else { write(copy the contents of the buffer to a temp array); }

      ---

      A broader idea might be "OutputStream extends WritableByteChannel", however, Channel has isOpen() method, and I do not see what a default implementation in OutputStream could look like.

      Alan Bateman (see https://github.com/openjdk/jdk/pull/16879#discussion_r1413859006): "Interesting but I don't think that is workable as WBC specifies that writes executing serially and also specifies the exception when attempting to write to a closed channel, both of which are not compatible with OutputStream."

            Unassigned Unassigned
            vsitnikov Vladimir Sitnikov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: