RFR: 8371718: (sc) Channels.new{Input, Output}Stream can allocate unbounded memory for a socket channel [v3]

Alan Bateman alanb at openjdk.org
Tue Dec 9 08:08:05 UTC 2025


On Mon, 8 Dec 2025 21:41:38 GMT, Brian Burkhalter <bpb at openjdk.org> wrote:

>> Clamp read and write to 128k bytes.
>
> Brian Burkhalter has updated the pull request incrementally with one additional commit since the last revision:
> 
>   8371718: Move limit retrieval outside loop

src/java.base/share/classes/sun/nio/ch/ChannelOutputStream.java line 76:

> 74:             if (n <= 0)
> 75:                 throw new RuntimeException("no bytes written");
> 76:             bb.limit(limit);

Setting the limit twice per iteration is a bit confusing, maybe simplify this loop to:

        int pos = bb.position();
        int rem = bb.limit() - pos;
        while (rem > 0) {
            bb.limit(pos + Math.min(MAX_BUFFER_SIZE, rem));
            int n = channelWrite(bb);
            if (n <= 0)
                throw new RuntimeException("no bytes written");
            pos += n;
            rem -= n;
        }

In passing, the pre-existing throwing of RuntimeException should be re-examined at some point.

src/java.base/share/classes/sun/nio/ch/SocketChannelImpl.java line 61:

> 59: import static java.net.StandardProtocolFamily.INET6;
> 60: import static java.net.StandardProtocolFamily.UNIX;
> 61: import static sun.nio.ch.Streams.MAX_BUFFER_SIZE;

This is not generally useful for the SocketChannel implementation, it is instead for the sole use of the methods that take an input/output stream. So I think better to use Streams.MAX_BUFFER_SIZE in the two methods rather than static import.

test/jdk/java/nio/channels/Channels/SocketChannelStreams.java line 76:

> 74:      * Test writing and reading an array of bytes.
> 75:      */
> 76:     public void testWriteRead() throws Exception {

I don't think this test is useful as there are a lot of tests here that do this. I think the test for this change will use a custom ByteChannel implementation that fails if called with a buffer that are >128k remaining.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/28705#discussion_r2601514295
PR Review Comment: https://git.openjdk.org/jdk/pull/28705#discussion_r2601462657
PR Review Comment: https://git.openjdk.org/jdk/pull/28705#discussion_r2601522666


More information about the nio-dev mailing list