java.lang.String hashCode and @Stable ?

forax at univ-mlv.fr forax at univ-mlv.fr
Fri Apr 11 08:53:37 UTC 2025


> From: "Glavo" <zjx001202 at gmail.com>
> To: "Chen Liang" <chen.l.liang at oracle.com>
> Cc: "Remi Forax" <forax at univ-mlv.fr>, "core-libs-dev"
> <core-libs-dev at openjdk.org>
> Sent: Thursday, April 10, 2025 8:54:57 PM
> Subject: Re: java.lang.String hashCode and @Stable ?

> Hi Chen,
> I think we can choose an arbitrary non-zero number and assign it to the `hash`
> field when the calculated hash is 0.

Usually yes, for String no. 
String.hashCode() computation is fully specified in the javadoc so changing the returned value is not a backward compatible change. 

When you compile a switch(String) the compiler computes the hashCode of the cases and switch on those values, so those hashCode values are inserted in the bytecode. 
If you change the algorithm of String.hashCode(), the runtime value and the compiled value will not be the same. 

regards, 
Rémi 

> Glavo

> On Fri, Apr 11, 2025 at 2:16 AM Chen Liang < [ mailto:chen.l.liang at oracle.com |
> chen.l.liang at oracle.com ] > wrote:

>> Hi Remi,
>> I think this is probably due to these fields being added too early - the stable
>> on string byte array is also added lately.

>> That said, I don't think adding stable on both fields completely resolves the
>> constant folding issues around string hash code. The current code can only
>> constant fold non-zero hash; a zero hash is folded to a read to hash field,
>> which cannot fold further because it's a read of the default value from a
>> stable field.
>> A solution may be to change hashIsZero to a byte field indicating 3 states -
>> hash unset (0), hash computed to field, hash computed and is zero. This allows
>> the zero hash to constant fold as well at the cost of non-constant hash access
>> performance, as now there are two reads.

>> Also this reminds me of [ https://bugs.openjdk.org/browse/JDK-8332249 |
>> https://bugs.openjdk.org/browse/JDK-8332249 ] - maybe Method::hashCode was hot
>> because the string hash code could not fold.

>> Regards, Chen

>> From: core-libs-dev < [ mailto:core-libs-dev-retn at openjdk.org |
>> core-libs-dev-retn at openjdk.org ] > on behalf of Remi Forax < [
>> mailto:forax at univ-mlv.fr | forax at univ-mlv.fr ] >
>> Sent: Thursday, April 10, 2025 4:18 AM
>> To: core-libs-dev < [ mailto:core-libs-dev at openjdk.java.net |
>> core-libs-dev at openjdk.java.net ] >
>> Subject: java.lang.String hashCode and @Stable ?
>> Question,
>> why String.hash and String.hashIsZero are not declared @Stable ?

>> regards,
>> Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250411/c13e5f6a/attachment.htm>


More information about the core-libs-dev mailing list