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

Add Writer.of(StringBuilder)

XMLWordPrintable

    • Icon: CSR CSR
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • core-libs
    • None
    • minimal
    • This is a new static method, should be no compatibility risk.
    • Java API
    • SE

      Summary

      New static factory method Writer of(StringBuilder) on java.io.Writer to return a Writer that writes characters into the given StringBuilder.

      Problem

      java.io.Writer is specified to be "Abstract class for writing character streams." Yet, there is no convenient way to create a Writer targeting a StringBuilder.

      The motivation for the new method is performance. Without this new method, writing directly into a StringBuilder is not possible, but is performed by writing into synchronized class StringWriter (the overhead increased when biased locked was removed), then copying the result using toString(), then copying again the String's content into StringBuilder. Once subsequent writing into the StringBuilder is needed (which is the stereotypic use case for StringBuilder), this chain-of-copies (and of synchronized blocks) starts again and again.

      Solution

      Add a new static factory method public static Writer of(StringBuilder) to Writer.

      Add API note to java.io.StringReader indicating it is superseded by Reader::of in non-thread-safe contexts.

      Notes

      This is the symmetric API to Reader.of(CharSequence) added in JDK 24 (see CSR), but limited to the specific class StringBuilder for sake of simplicity, instead of targeting any Appendable.

      Specification

      /**
       * Returns a {@code Writer} that writes characters into a
       * {@code StringBuilder}. The writer is initially open and writing appends
       * after the last character in the string builder.
       *
       * <p> The resulting writer is not safe for use by multiple
       * concurrent threads. If the writer is to be used by more than one
       * thread it should be controlled by appropriate synchronization.
       *
       * <p> If the string builder changes while the writer is open, e.g. the length
       * changes, the behavior is undefined.
       *
       * @param sb {@code StringBuilder} consuming the character stream.
       * @return a {@code Writer} which writes characters into {@code sb}.
       * @throws NullPointerException if {@code sb} is {@code null}
       *
       * @since 25
       */
      public static Writer of(StringBuilder sb) {

            mkarg Markus Karg
            mkarg Markus Karg
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: