Subodh Joshi
Subodh Joshi

Reputation: 13492

In Java Serlization which Serial version ID generation approach we have to use?

If i implementing Serializable on every class of my application so that application can be easily run on Jboss cluster environment.

Now if i implemented Serializable in my classes ,eclipse showing below message

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

Now it is giving me three options

  1. Add Default Serial version ID
  2. Add generated Serial version ID
  3. Add @SuppressWarings to 'serial'

If i will choose first it will generate like this

  private static final long serialVersionUID = 1L;

If i will choose second it will generate like this

  private static final long serialVersionUID = 1629728947486980072L;

Third we can easily ignore because we have to run the application in cluster environment so we have to add versionID anyhow What is a serialVersionUID and why should I use it?

Now as i told i have to implement serialization each and very class which one is better approach. Approach1 or Appraoch2?

  1. Add Default Serial version ID
  2. Add generated Serial version ID

Upvotes: 1

Views: 1016

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

A serialVersionUID poses a logical burdon: it should be carefully maintained.

Its implicit generation (the compiler hashes method signatures and such), is limited. So no supressing of warnings.

Optimally the version should stay the same as long as possible, and possibly update persisted objects of older class definitions.

At least on a new class definition, the serialVersionUID must be changed.

To make that change more attractive, I use a serialVersionUID in the form of date time yyyyMMddHHmm:

 private static final long serialVersionUID = 201508171605L;

For date time 2015-08-17T16:05.

BTW: a good opportunity to apply underscores:

 private static final long serialVersionUID = 2015_08_17__16_05L;

This makes an overseen version UID more easily identifiable.

Upvotes: 2

Gawron
Gawron

Reputation: 85

The java.io.Serializable doc says:

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.

So you can think of serialVersionUID as of the 'hash code' of your class. Therefore, second approach is definitely better, as the first is very similar (almost equal) to Add @SuppressWarings to 'serial'.

For more information, visit this blog.

Upvotes: 0

Related Questions