RFR: 8358624: ImmutableDescriptor violates equals/hashCode contract after deserialization [v2]

Kevin Walls kevinw at openjdk.org
Mon Jun 23 10:13:34 UTC 2025


On Fri, 20 Jun 2025 19:30:27 GMT, Chris Plummer <cjplummer at openjdk.org> wrote:

> I'm not much of a serialization expert, so just asking for some clarification here. I assume when de-serialized, the initial hashcode is always 0. Why it is 0 and not by default -1. Seems this would be an issue with any de-serialized type and all would need to explicitly set to -1 as you have done in this case.

As a transient field the hashCode int is not restored by serialization.  But why zero, and not -1 as per the field declaration?

The -1 is set by a constructor in ImmutableDescriptor.

ObjectInputStream:
"Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specific class."

I think that is the explanation: it's all zero'd, and the constructor that would set the -1 doesn't get called.

I see another example (src/java.management/share/classes/javax/management/openmbean/ArrayType.java) where we implement a hashCode member as "private transient Integer  myHashCode = null; "  There we check if that is null, which causes re-calculating of the hashCode on demand after deserialization.  That gets default behaviour of recalculating, but uses a Java object.

This class used a primitive field, I didn't want to change much in this obscure old class.

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

PR Comment: https://git.openjdk.org/jdk/pull/25758#issuecomment-2995805998


More information about the serviceability-dev mailing list