Noticed this when backporting JDK-8325730. There is a seemingly long-standing disconnect between the specification of AbstractStringBuilder.toString:
```
/**
* Returns a string representing the data in this sequence.
* A new {@code String} object is allocated and initialized to
* contain the character sequence currently represented by this
* object. This {@code String} is then returned. Subsequent
* changes to this sequence do not affect the contents of the
* {@code String}.
*
* @return a string representation of this sequence of characters.
*/
@Override
public abstract String toString();
```
I read it as: a new string is _always_ allocated with `toString()`.
But this behavior was subtly changed withJDK-8240094 that started to return the same "" literal string for empty state. JDK-8282429 "regressed" it back to conformant behavior. JDK-8325730 regressed the "regression" by starting to return "" again, which again put us into non-spec behavior.
We need to decide which way we should go. Seeing that there are no customer reports about reliance on this behavior, and that nothing, including the tests, have noticed the compatibility problem here, maybe we should just update the spec.
```
/**
* Returns a string representing the data in this sequence.
* A new {@code String} object is allocated and initialized to
* contain the character sequence currently represented by this
* object. This {@code String} is then returned. Subsequent
* changes to this sequence do not affect the contents of the
* {@code String}.
*
* @return a string representation of this sequence of characters.
*/
@Override
public abstract String toString();
```
I read it as: a new string is _always_ allocated with `toString()`.
But this behavior was subtly changed with
We need to decide which way we should go. Seeing that there are no customer reports about reliance on this behavior, and that nothing, including the tests, have noticed the compatibility problem here, maybe we should just update the spec.
- relates to
-
JDK-8325730 StringBuilder.toString allocation for the empty String
- Closed
-
JDK-8240094 Optimize empty substring handling
- Resolved
-
JDK-8282429 StringBuilder/StringBuffer.toString() skip compressing for UTF16 strings
- Resolved