Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Serial version id for all the classes?

Java specification stats that

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.enter code here

But If I assign all the classes same serial version id as follows

static final long serialVersionUID = 1L;

Now all my classes will have same serialversionUID and this will never result in InvalidclassException.

I know that we give it explicitly so that its value remains constant across different JVM implementations.

Please let me know what is the use of putting same id for all the classes and what will happen if we modify class in between serialization and deserialization ?

like image 240
ankit Avatar asked Sep 25 '14 17:09

ankit


1 Answers

I believe the serialVersionUID is only used to determine the version of that class that has been serialized - the class name is always present too, so it won't lead to any ambiguity.

Please let me know what is the use of putting same id for all the classes

They're effectively unrelated values. It's just simple to use 1 and increment it every time you make a breaking change.

what will happen if we modify class in between serialization and deserialization ?

That entirely depends on the type of modification you make. If you're just adding or removing methods, or static fields, it's fine - that wouldn't affect the serialized data anyway. If you make any changes to instance fields, that's when life gets hairy. You'd need to study the serialization format in detail to work out exactly what would constitute a breaking change, but it's entirely possible that just changing the name of a field could break things - e.g. if fields are serialized in name order.

You might want to consider using a binary data format which plays a bit more pleasantly with data format changes, such as Protocol Buffers. (There are other benefits available too, such as portability and speed - and protobuf isn't the only game in town, either.)

like image 106
Jon Skeet Avatar answered Oct 12 '22 13:10

Jon Skeet