Java

SerialVersionUID in java

SerialVersionUID in Java

Java serialization process associates each Serializable class a version number which is called SerialVersionUID (also known as Stream Unique Identifier). It is used to ensure that during deserialization the same class (that was used during serialize process) is loaded.

Declaration:

private static final long serialVersionUID = 3487495895819393L;

All the serializable classes must declare serialVersionUID but if the class doesn’t declare, then JVM calculates the same and saves it along with the data being serialized. The serialVersionUID should be unique for every Serializable class in your system.

 

When the class is serializable and it doesn’t define the serialVersionUID, then JVM calculates the same. It uses Secure Hash Algorithm which is a 64-bit hash of the class name, interface class names, methods, and fields. The value is fixed for all compatible classes. If the SUID is not declared for a class, the value defaults to the hash for that class.

How serialVersionUID works?

  • When an object is serialized, the serialVersionUID is serialized along with the other contents.
  • Later when the same is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.
  • If the numbers do not match then, InvalidClassException is thrown.
  • If the loaded class is not having a serialVersionUID declared, then it is automatically generated by JVM using the same algorithm as before. But there are some concerns when JVM generates the SerialVersionUID stated below.

 

 

Output:

 

Problem of depending on default SerialVersionUID generated by JVM

  • Both sender and receiver should use the same JVM with respect to platform and version also. Otherwise receiver will be unable to deserialize because of different SerialVersionUID.
  • Both sender and receiver should use same .class file version. After serialization if there is any change in .class file at receiver side then receiver unable to deserialize.
  • To generate SerialVersionUID internally JVM may use complex algorithm which may create performance problem.

 

When serialVersionUID is different during deserialization

When an object is serialized, the serialVersionUID is serialized along with the other contents. Later when that is deserialized, the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class. If the numbers do not match then, InvalidClassException is thrown.

Hence its always recommended to declare serialVersionUID ourselves in the class rather than passing the responsibility to JVM.

 

Happy Learning!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.