Using serialVersionUID

This tutorial explains the importance of versioning Serializable objects using serialVersionUID.

1. Introduction

In Java whenever a class implements java.io.Serializable we get a warning saying.

“The serializable class Student does not declare a static final serialVersionUID field of type long”

Serializable_warning

when we auto fix this warning by generating a default serial version, eclipse adds the the below lines.

Serializable_fix

2. POJO Class

Lets create a simple serializable POJO class Student.java

3. Main Class to serialize and de-serialize the above POJO

The below class two methods one which creates a new Student object, populates with values and serializes, whereas other method reads the serialized object and prints the fields.

4. First Run

Output1

5. Change Serial Version and de serialize.

Lets change the serialVersionUID in the Student.java 

next in the Serializor.java lets comment the line which serializes and try to de-serialize the Student object previously serialized.

6. Second Run

When we run the same program again after making the above changes, we get the below exception

7.  Conclusion

  1. The second run above failed because the serialVersionUID changed after the serialization had taken place.
  2. Usually in Distributed Systems the system which serializes might not always be the one to de-serialize it, for example. a server might serialize an object and then a client might de-serialize it. Hence its of utmost importance to add serialVersionUID to all Serializable classes.
  3. If we dont specify a serialVersionUID then the JVM automatically adds one and the algorithm for generating the same is different across different JDKs example, Sun JDK and Open JDK might generate a different serialVersionUID for the same Class.
  4. Its always a good practice to start the serialVersionUID from 1L whenever we modify the class we increment this number by 1 so that it fails in case the other person doesn’t have the latest version.

I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.

Comments

  1. By Sundar

    Reply

    • By Manjunath

      Reply

  2. By Shaikkh Valli

    Reply

    • By manju

      Reply

  3. By Dinesh Devasagayam

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *