On Mon, 4 Dec 2023 14:05:14 GMT, Vladimir Sitnikov <vsitni...@openjdk.org> wrote:
>>> > it doesn't solve the second part of the concern which is read-only view >>> > on the internal buffer. >>> >>> I think `ByteBuffer.asReadOnlyBuffer()` should resolve the issues regarding >>> naked byte access. At least `ByteBuffer#array()` returns `null` for >>> read-only buffers, and `ByteBuffer#hasArray()` returns `false`. Am I >>> missing something? >> >> The backing array is not frozen so a read-only view doesn't address the >> second part of the concern where the target keeps a reference. > >>The backing array is not frozen so a read-only view doesn't address the >>second part of the concern where the target keeps a reference. > > The users outside of OpenJDK would not have a reference to `byte[]`. > Do you mean a reference to `ByteBuffer`? > What if there was a `ByteBuffer#forbidReads()` method that would permanently > forbid subsequent reads from the `ByteBuffer`? I've created a draft change for `OutputStream#write(ByteBuffer)`, and I have benchmarked several cases including `ByteArrayInputStream.transferTo(BufferedOutputStream(ByteArrayOutputStream))`, `ByteArrayInputStream.transferTo(DataOutputStream(FileOutputStream))`. Benchmarks show there's improvement in both allocation rate and latency. Read-only `ByteBuffers` can address poisoning concerns as non-jdk code can't peek into read-only arrays. The `write(ByteBuffer)` approach supports cases like `CheckedOutputStream`, `DataOutputStream` which would be hard or impossible to optimize when passing naked byte arrays. Here are the results: https://gist.github.com/vlsi/7f4411515a4f2dbb0925fffde92ccb1d Here is the diff: https://github.com/vlsi/jdk/compare/ce108446ca1fe604ecc24bbefb0bf1c6318271c7...write_bytebuffer @mkarg , @bplb , @AlanBateman , could you please review `OutputStream.write(ByteBuffer)` approach? ------------- PR Review Comment: https://git.openjdk.org/jdk/pull/16879#discussion_r1428725435