Typefully

Java: What is serialVersionUid

Avatar

Share

 • 

4 years ago

 • 

View on X

Java - What is serialVersionUid (SVU)? a thread...
The serialVersionUid is a version no of the serializable class. During de-serialization JVM matches serialVersionUid against the de-serialized object to check the compatibility with serialized class.
Consider below Employee class with serialVersionUid=1L
Let's store the serialized object into a txt file:
Let's change serialVersionUid to 2L:
Now, let's try to de-serialize it from the same emp.txt file again with the new serialVersionUid=2L.
This time our code will fail and result in InvalidClassException.
If no SVU is defined, then JVM will automatically assign one, by using variables, methods, static fields in a class. In the future, when our class changes the default SVU will also change which may cause unexpected behavior. Hence, it is good practice to define SVU explicitly.
When to update SVU? When a new version of the class isn't backward compatible and needs to break the de-serialization process. For e.g: 1. Changing type of fields to incompatible (string to int) 2. Removing existing fields 3. Or when need to discontinue the old version of POJO.
When not to update? As far as our new version of class is backward compatible we can use same SVU. For e.g: 1. Adding new fields in POJO. 2. Changing to a DT which is compatible with old version (For. e.g. int to long) 3. When you don't want to break de-serialization.
Thanks for reading, hope you learnt something new! If you like this then you might also like reading this: twitter.com/vikasrajputin/status/1526737086283321345
Namaste, I'm Vikas! I write a thread every Mon, Wed & Fri on Java, Javascript & Fullstack Development. To read all my future threads follow @vikasrajputin Any Query, Feedback & Suggestions? Put them in the comments below. Happy Coding!
Avatar

Vikas Rajput

@vikasrajputin

Sr. Backend Engineer. Simplifying Backend and sharing what I learn along the way. Building Gujarat's biggest java community at @juggujarat