Understand the serialVersionUID

If you have ever implemented Serializable interface, you must encounter this warning message


The serializable class xxx does not declare a static final serialVersionUID field of type long

So…what is serialVersionUID?

The serialVersionUID is used as a version control in a Serializable class. If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various aspects of your Serializable class, as described in the Java(TM) Object Serialization Specification.

1. SerialVersionUID Example

The above statement is a bit hard to understand at the beginning (at least I did), let start an example to understand how Serializable class use SerialVersionUID to implement version control.

1.1 Address.java

A serializable class with a serialVersionUID of 1L.


import java.io.Serializable;
 
public class Address implements Serializable{
 
	   private static final long serialVersionUID = 1L;
	
	   String street;
	   String country;
 
	   public void setStreet(String street){
		   this.street = street;
	   }
 
	   public void setCountry(String country){
		   this.country = country;
	   }
 
	   public String getStreet(){
		   return this.street;
	   }
 
	   public String getCountry(){
		   return this.country;
	   }
 
	   @Override
	   public String toString() {
    	   return new StringBuffer(" Street : ")
    	   .append(this.street)
    	   .append(" Country : ")
    	   .append(this.country).toString();
	   }
}

1.2 WriteObject.java

A simple class to write / serialize the Address object into a file – “c:\\address.ser”.


import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
 
public class WriteObject{
 
	public static void main (String args[]) {
	 
	   Address address = new Address();
	   address.setStreet("wall street");
	   address.setCountry("united states");
 
	   try{
 
		FileOutputStream fout = new FileOutputStream("c:\\address.ser");
		ObjectOutputStream oos = new ObjectOutputStream(fout);   
		oos.writeObject(address);
		oos.close();
		System.out.println("Done");
 
	   }catch(Exception ex){
		   ex.printStackTrace();
	   } 
	}
}

1.3 ReadObject.java

A simple class to read / deserialize the Address object from file – “c:\\address.ser”.


import java.io.FileInputStream;
import java.io.ObjectInputStream;
 
public class ReadObject{
 
   public static void main (String args[]) {
 
	   Address address;
	   
	   try{
 
		   FileInputStream fin = new FileInputStream("c:\\address.ser");
		   ObjectInputStream ois = new ObjectInputStream(fin);
		   address = (Address) ois.readObject();
		   ois.close();
 
		   System.out.println(address);
		   
	   }catch(Exception ex){
		   ex.printStackTrace(); 
	   } 
   }
}

2. Testing

Let do some testing to demonstrate the use of serialVersionUID.

2.1 Same serialVersionUID

Same serialVersionUID , there is no problem during the deserialization process


javac Address.java
javac WriteObject.java
javac ReadObject.java
java WriteObject
java ReadObject
Street : wall street Country : united states

2.2 Different serialVersionUID

In Address.java, change the serialVersionUID to 2L (it was 1L), and compile it again.


javac Address.java
java ReadObject
java.io.InvalidClassException: Address; local class incompatible: 
stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
        ... 
        at ReadObject.main(ReadObject.java:14)

The “InvalidClassException” will raise, because you write a serialization class with serialVersionUID “1L” but try to retrieve it back with updated serialization class, serialVersionUID “2L”.

The serialVersionUID have to match during the serialization and deserialization process.

When should update your serialVersionUID?
When your serialization class is updated with some incompatible Java type changes to a serializable class, you have to update your serialVersionUID.

For detail about the compatible and incompatible Java type changes to a serializable class, see the Java Object Serialization Specification.

3. What’s wrong with the default serialVersionUID?

If no serialVersionUID is declared, JVM will use its own algorithm to generate a default SerialVersionUID, you can check the algorithm here.

The default serialVersionUID computation is highly sensitive to class details and may vary from different JVM implementation, and result in an unexpected InvalidClassExceptions during the deserialization process.

3.1 Client / Server environment

– Client is using SUN’s JVM in Windows.
– Server is using JRockit in Linux.

The client sends a serializable class with default generated serialVersionUID (e.g 123L) to the server over socket, the server may generate a different serialVersionUID (e.g 124L) during deserialization process, and raises an unexpected InvalidClassExceptions.

3.2 File / Database environment

– App #1 is using SUN’s JVM in Windows.
– App #2 is using JRockit in Linux.

Serialization has allowed to save into a file or database. App #1 stores a serializable class into database by default generated serialVersionUID (e.g 123L), while App #2 may generate a different serialVersionUID (e.g 124L) during deserialization process, and raise an unexpected InvalidClassExceptions.

You can check here for the List of the JVM implementation.

4. How to generate serialVersionUID

You can use JDK “serialver” or Eclipse IDE to generate serialVersionUID automatically, see detail.

Conclusion

SUN is highly recommended developers to declare the serialVersionUID in order to avoid the different JVM issue listed above, however I rather recommend you should understand what is serialization, how serialVersionUID implement version control and why your class need to use serialization. Understand the serialVersionUID concept is better than blindfold to any recommendation.

References

  1. http://en.wikipedia.org/wiki/List_of_JVM_implementations
  2. http://java.sun.com/javase/6/docs/platform/serialization/spec/class.html#4100
  3. http://stackoverflow.com/questions/419796/explicit-serialversionuid-considered-harmful
  4. http://en.wikipedia.org/wiki/Serialization#Java
  5. http://www.javaworld.com/javaworld/jw-02-2006/jw-0227-control.html?page=1
  6. http://www.javablogging.com/what-is-serialversionuid/
  7. http://java.dzone.com/articles/dont-ignore-serialversionuid
  8. http://www.java-forums.org/new-java/8196-serialversionuid.html

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Hemalatha Kandagiri
Guest
Hemalatha Kandagiri

I understood a bit. My doubt is, But I am not sure. can two different classes like class A and Class B can have same serialize ID? Pelase correct me if my question is wrong

sujaan kumar
Guest
sujaan kumar

Hi mkyoung,
very good explanation.
As we know that serializable is a marker interface it doesn’t contain any method or variable ,when we are not define the serialVersionUID explicitly then JVM put a default one.my question is from where this static final variable comes from.

infoj
Guest
infoj

The stream-unique identifier is a 64-bit hash of the class name, interface class names, methods, and fields.
Also from Java docs – http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations

Deepak Pandey
Guest
Deepak Pandey

serialversionUID is static does it also serialize with class. if YES then how it can get serialize as it is static field , it is not stored on heap so its not related to object but related to class. If NO then how jvm finds that the class we are deserialize is same . Please explain working of SerialiversionUID. Thanks in advance

Deepak Pandey
Guest
Deepak Pandey

Please explain If anyone have answer to this question

rajneekanth
Guest
rajneekanth

good one.

Raj Parekh
Guest
Raj Parekh

Very well explained. Thank you.

Zia Ulhaq
Guest
Zia Ulhaq

i have a question.. can i initiate any value for serialVersionUID ?

koma
Guest
koma

why “serialVersionUID” should be lower case when it’s a constant?

Rakesh Yadav
Guest
Rakesh Yadav
Hi Mr yong, its very easy and nice example to understand serialVersionUID, I appreciate your work and thanks for sharing. ************************************************************************************* We are generating a web based application, as part of this we need to use a number of Applets. But the problem is again with serialVersionUID. java.io.InvalidClassException: XYZ local class incompatible: stream classdesc serialVersionUID = -962022720109015502, local class serialVersionUID = 532615968316031794 Here the problem is we need to use predefined class, where I can’t change serialVersionUID (my assumption). and as this is the web based application, I’m not supposed to force all my clients to use specific JRE. Please… Read more »
ggsongnail
Guest
ggsongnail

I have question “Unknown column ‘serialVersionUID’ in ‘order clause'” how to solve it? thx

merlin
Guest
merlin

Hi, mkyong, I have read a lot of your technical blogs about java, and they really help me so much. I post this comment just to express my appreciation, thank you very much.

Nitin
Guest
Nitin

Thanks yong it is very useful content.

Kamal Giri
Guest
Kamal Giri

Thank you MKYONG for Sharing this tutorial.

prashanth
Guest
prashanth

Hi,
In my project there are 100’s of Classes are derived from Serializable interface, but serialVersionUID not used manually. Till now its working fine. Now its giving the java.io.InvalidClassException. I am unable change all my existing classes.

Please tell me the solution with out adding serialVersionUID manually how to solve this problem.

Thanks in advance.

Regards,
Prashnath

sarath
Guest
sarath

it may be because of you have made few edit in the code..
redo all it will solve your problem i think.

trackback
How to generate serialVersionUID

[…] Understand the serialVersionUID and how to use it. Tags : java serialversionuid mkyong Founder and Chief Editor of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. […]

Sebastian
Guest
Sebastian

@mkyong

Thanks for your work on this blog. Each time I have a doubt with Java I end up here and resolving my issue ALWAYS. Thanks again!

Zaf
Guest
Zaf

Thanx for ur description, its helpful :)

Amol Dake
Guest
Amol Dake

your site is really very helpful,I appreciate your work…

Samella Geiser
Guest
Samella Geiser

I do believe all of the ideas you’ve introduced to your post. They are really convincing and can certainly work. Nonetheless, the posts are too quick for beginners. May just you please extend them a little from subsequent time? Thanks for the post.

Janak Porwal
Guest
Janak Porwal

Thanks…. simple, neat explanation with good advice.

krisha
Guest
krisha

uhm, since i am still studying i am not yet familiar with everything in making programs .. i just wanna ask BOUT HOW WILL I EXPLAIN IF I USED serialVersionUID in my program?

y s rao
Guest
y s rao

Hi Thanks. nice explanation.

What i understand from your explanations is : the serial version id should be same for the class while serialization / de-serialization. If so, why java people left this to the developers. why they did not assigned some constant value (by default) to each and every class that we create, instead of assigning the value by some calculation?.

Thanks
Y S Rao

yuyuchen09
Guest
yuyuchen09

When there is enough changes that should honor an new version. That gives developer the option to invalidate the older version already installed, and make it incompatible.

trackback
What is use of serialVersionUID « JAVA

[…] Ref Url : If you ever implemented Serializable interface, you must encounter this warning message […]

Sandeep
Guest
Sandeep

That saved the day for me. :)

trackback
Blog bookmarks 01/20/2010 « My Diigo bookmarks

[…] Understand the serialVersionUID | Java Best Practices […]

Artur Biesiadowski
Guest
Artur Biesiadowski
@cjiang Java serialization is a more efficient than automatic xml serialization – in each of processing memory, wire usage and cpu usage to encode and decode. For manual xml serialization, you can also expect it to be considerably faster. Said that, there are other ways to be even faster than that – for example take a look at Hessian http://hessian.caucho.com/ As far as serializing/deserializing on different JVMs is concerned, I thought that this issue was mainly tied to different compilers, which can create different synthetic methods. For same binary class file, serialVersionUID should be deterministic AFAIK ? Maybe mkyong can… Read more »
cjiang
Guest
cjiang

Artur,
Thank you for the reply.

cjiang
Guest
cjiang

Need your help with two questions.
1) Are all jvm implementations always confirming to the java serialization spec? ie. if I serialize a Java object in sun jvm, can I always be able to deserialize it in JRocket or IBM’s jvm providing the serialVersionUID is the same?
2) Will serialization form using java serializable mechanism consume more memory than using xml representation?

Thanks.

afon
Guest
afon

Good and interesting explanation. thanks.