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

ByteArrayOutputStream.writeTo(OutputStream) pins carrier

XMLWordPrintable

    • b21

        All BAOS operations are synchronized since early JDK releases. While undocumented, there are compatibility concerns with dropping the synchronization that have prevented its removal.

        For virtual threads the BAOS.writeTo method is problematic as writing to the target output stream may block indefinitely and prevent a carrier thread from being released when writeTo is invoked from a virtual thread. This will be non-issue when the object monitors work is in a JDK release. In the mean-time, it may require a workaround. Replacing the synchronization with j.u.concurrent lock when a BAOS is directly used (not subclassed) is technically possible but it changes the performance in subtle ways. Instead, it may be simpler to just work around the issue with the one method with:

        ```
            public void writeTo(OutputStream out) throws IOException {
                if (Thread.currentThread().isVirtual()) {
                    out.write(toByteArray());
                } else synchronized (this) {
                    out.write(buf, 0, count);
                }
            }
        ```

        That is, take a (potentially costly) snapshot of the bytes and write them to the target output stream. The only compatibility concern is where something is relying on the undocumented synchronized and expects a concurrent write + writeTo be execute sequential rather than concurrently.

              bpb Brian Burkhalter
              alanb Alan Bateman
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated:
                Resolved: