Why generate long serialVersionUID instead of a simple 1L?
When class implements Serializable in Eclipse, I have two options: add default serialVersionUID(1L)
or generated serialVersionUID(3567653491060394677L)
. I think that first one is cooler, but many times I saw people using the second option. Is there any reason to generate long serialVersionUID
?
As far as I can tell, that would be only for compatibility with previous releases. This would only be useful if you neglected to use a serialVersionUID before, and then made a change that you know should be compatible but which causes serialization to break.
See the Java Serialization Spec for more details.
The purpose of the serialization version UID is to keep track of different versions of a class in order to perform valid serialization of objects.
The idea is to generate an ID that is unique to a certain version of an class, which is then changed when there are new details added to the class, such as a new field, which would affect the structure of the serialized object.
Always using the same ID, such as 1L
means that in the future, if the class definition is changed which causes changes to the structure of the serialized object, there will be a good chance that problems arise when trying to deserialize an object.
If the ID is omitted, Java will actually calculate the ID for you based on fields of the object, but I believe it is an expensive process, so providing one manually will improve performance.
Here's are a couple of links to articles which discuss serialization and versioning of classes:
- JDC Tech Tips: February 29, 2000 (link broken as of February 2013)
- Discover the secrets of the Java Serialization API
The main reason for the generated one would be to make it compatible with an existing version of the class that already has persisted copies.