I have a discussion with a colleague about the serialVersionUID of serializable classes: He always start with a serialVersionUID = 1L
and then increments it by one when there are some significant changes to the class.
The JDK classes always seem to use more complex, generated
serialVersionUIDs like in the java.lang.String
class:
private static final long serialVersionUID = -6849794470754667710L;
Now my colleague asks about the advantage of this kind of serialVersionUID versus much simpler serialVersionUID like 1L, 2L, 3L... ?
We also searched on SOF, but are not very satisfied with the answers given, for example in Why generate long serialVersionUID instead of a simple 1L?.
In my opinion the advantage of using generated IDs is that it does not need any information about the 'older' class versions. But when incrementing the IDs manually, you have to know the highest value so far. This might sound trivial (by just looking at the current serialVersionUID and increase it by 1) but could be more complex in bigger software projects, bigger development teams or in distributed environments.
The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.
Technically you can't prevent two classes from having the same serial version UID, much like you can't prevent two objects from having the same system hash code.
SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.
The advantage of using a generated one is that it is compatible with the prior version of the class if it has escaped without a serialVersionUID
into the wild.
Having said that, your colleague is almost certainly wrong to increment it. The serialVersionUID
should only be changed at a point where you accept that the class has changed irretrievably and you deliberately want to introduce a serialization-incompatibility. The times when this occurs in nature are rare, being confined to the cases where you change the inheritance of the class or the types of member fields in an incompatible way. If you've decided to make a class Serializable
you should already have accepted a regime in which that doesn't occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With