RFR: 8353795: Add Writer.of(StringBuilder)

Markus KARG duke at openjdk.org
Sun Apr 6 09:39:47 UTC 2025


On Sat, 5 Apr 2025 17:36:29 GMT, Markus KARG <duke at openjdk.org> wrote:

> This Pull Requests proposes an implementation for [JDK-8353795](https://bugs.openjdk.org/browse/JDK-8353795): Adding the new method `public static Writer Writer.of(StringBuilder)`, providing a non-synchronized Writer implementation optimized for writing into `StringBuilder`.
> 
> A basic test is provided to proof that the new `Writer` behaves as expected. For comparison, the same test is also run against `StringWriter`.

Continuing from thread "[Request for Enhancement: java.io.Writer.of(Appendable) as an efficient alternative to java.io.StringWriter](https://mail.openjdk.org/pipermail/core-libs-dev/2025-March/141539.html)":

@liach wrote:
>...we can probably start drafting the API documentation of this new API `Writer.of(StringBuilder)`:
>```java
>@return a character stream that redirects to a specified StringBuilder}
><p>
>The {@code write} and {@code append} invocations are redirected to the {@code append} methods with the same parameter t>ypes on the specified StringBuilder, except {@code write(int)}, which delegates to {@code append(char)}. The {@code flush} and >{@code close} invocations have no effect.
>```
>I propose to specify this explicitly as a delegation proxy; we can infer the lack of thread safety from `StringBuilder`. (If we want, we can add an API note asking to use `StringWriter` if thread safety is needed). Also, we don't specify the `toString` behavior on the returned Writer (unlike for `StringWriter`); I think users should just use the `toString` on the `StringBuilder`.

Actually I do not see the benefit of documenting which method redirects to what other method or class, but I see that it binds us in future to today's decisions. Also I do not see what benefit notes about `StringWriter` and `toString` would be good for, as leaving it open provides most future flexibility to change eventually (just as we leave open `hashCode` and `equals`).

Having said that, instead I started the PR with a typical JavaDoc as it looks like what we did in `Reader.of()` recently.

WDYT?

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

PR Comment: https://git.openjdk.org/jdk/pull/24469#issuecomment-2781332523


More information about the nio-dev mailing list