Monday, October 31, 2011

Why generate long serialVersionUID instead of a simple 1L?

Question:


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?

Answer:

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.

You absolutely should create a serialVersionUID every time you define a class that implements java.io.Serializable. If you don't, one will be created for you automatically, but this is bad. The auto-generated serialVersionUID is based on the method signatures of your class, so if you change your class in the future to add a method (for example), deserializing the "old" versions of the class will fail. Here's what can happen:

1. Create the first version of your class, without defining the
serialVersionUID
.
2. Serialize an instance of your class to a persistent store; a
serialVersionUID is automatically generated
for you.
3. Modify your class to add a new method, and redeploy your application.
4. Attempt to deserialize the instance that was serialized in step 2, but now it fails (when it should succeed), because it has a
different
auto-generated serialVersionUID.

No comments: