RFR: 8351443: Improve robustness of StringBuilder [v7]

Raffaello Giulietti rgiulietti at openjdk.org
Fri May 9 13:31:55 UTC 2025


On Fri, 9 May 2025 00:20:19 GMT, Roger Riggs <rriggs at openjdk.org> wrote:

>> Refactor AbstractStringBuilder to maintain consistency among count, coder, and value buffers while the buffer capacity is being expanded and/or inflated from Latin1 to UTF16 representations. 
>> The refactoring pattern is to read and write AbstractStringBuilder fields once using locals for all intermediate values. 
>> Support methods are static, designed to pass all values as arguments and return a value.
>> 
>> The value byte array is reallocated under 3 conditions:
>> - Increasing the capacity with the same encoder
>> - Increasing the capacity and inflation to change the coder from LATIN1 to UTF16
>> - Inflation with the same capacity
>> 
>> Added StressSBTest to exercise public instance methods of StringBuilder.
>
> Roger Riggs has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Add an assert to inflateToUTF16 method
>   Add doc of preconditions to appendChars... methods
>   Correct misc javadoc

src/java.base/share/classes/java/lang/AbstractStringBuilder.java line 238:

> 236:      * {@return true if the byte array should be replaced due to increased capacity or coder change}
> 237:      * <ul>
> 238:      *     <li>The new coder is the different than the old coder

Suggestion:

     *     <li>The new coder is different than the old coder

src/java.base/share/classes/java/lang/AbstractStringBuilder.java line 1901:

> 1899:         }
> 1900:         return value;
> 1901:     }

I think the logic can be simplified, without a need for the loop.

    private static byte[] putCharsAt(byte[] value, byte coder, int count, int index, char[] s, int off, int end) {
        if (isLatin1(coder)) {
            int latin1Len = StringUTF16.compress(s, off, value, index, end - off);
            if (latin1Len < end - off) {
                value = inflateToUTF16(value, count);
                StringUTF16.putCharsSB(value, index + latin1Len, s, off + latin1Len, end);
            }
        } else {
            StringUTF16.putCharsSB(value, index, s, off, end);
        }
        return value;
    }

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

PR Review Comment: https://git.openjdk.org/jdk/pull/24967#discussion_r2081686513
PR Review Comment: https://git.openjdk.org/jdk/pull/24967#discussion_r2081689712


More information about the core-libs-dev mailing list