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

【转载】 http://www.mkyong.com/java-best-practices/understand-the-serialversionuid/

【转载】Understand the serialVersionUID的更多相关文章

  1. local class incompatible: stream classdesc serialVersionUID = -2897844985684768944, local class serialVersionUID = 7350468743759137184

    local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2427 ...

  2. Java中serialVersionUID的解释及两种生成方式的区别(转载)

    转载自:http://blog.csdn.net/xuanxiaochuan/article/details/25052057 serialVersionUID作用:        序列化时为了保持版 ...

  3. 转载:AbstractQueuedSynchronizer的介绍和原理分析

    简介 提供了一个基于FIFO队列,可以用于构建锁或者其他相关同步装置的基础框架.该同步器(以下简称同步器)利用了一个int来表示状态,期望它能够成为实现大部分同步需求的基础.使用的方法是继承,子类通过 ...

  4. JAVA中SERIALVERSIONUID的解释

    serialVersionUID作用:        序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性.有两种生成方式:       一个是默认的1L,比如:private st ...

  5. [转载] Java高新技术第一篇:类加载器详解

    本文转载自: http://blog.csdn.net/jiangwei0910410003/article/details/17733153 首先来了解一下字节码和class文件的区别: 我们知道, ...

  6. 【转载】Recommendations with Thompson Sampling (Part II)

    [原文链接:http://engineering.richrelevance.com/recommendations-thompson-sampling/.] [本文链接:http://www.cnb ...

  7. 【转载】安卓APP架构

    注:本篇博文转载于 http://my.oschina.net/mengshuai/blog/541314?fromerr=z8tDxWUH 本文介绍了文章作者从事了几年android应用的开发,经历 ...

  8. JavaWeb防止表单重复提交(转载)

    转载自:http://blog.csdn.net/ye1992/article/details/42873219 在平时开发中,如果网速比较慢的情况下,用户提交表单后,发现服务器半天都没有响应,那么用 ...

  9. Java序列化中的SerialVersionUid

    版权声明:本文为博主fbysss原创文章,转载请注明出处 作者:fbysssmsn:jameslastchina@hotmail.com  blog:blog.csdn.NET/fbysss声明:本文 ...

随机推荐

  1. js 打印星星金字塔

    /** * * 第一行: * * 第二行: *** * 第三行: ***** * 第四行: ******* * 第五行: ********* * */ document.write('<p al ...

  2. 转自一个CG大神的文章

    <如何学好游戏3D引擎编程>此篇文章献给那些为了游戏编程不怕困难的热血青年,它的神秘要我永远不间断的去挑战自我,超越自我,这样才能攀登到游戏技术的最高峰           ——阿哲VS自 ...

  3. C#中ref,out

    out 关键字会导致参数通过引用来传递.这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化.若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字 比如 ...

  4. HDU 1026 Ignatius and the Princess I(带路径的BFS)

    http://acm.hdu.edu.cn/showproblem.php?pid=1026 题意:给出一个迷宫,求出到终点的最短时间路径. 这道题目在迷宫上有怪物,不同HP的怪物会损耗不同的时间,这 ...

  5. BOM和DOM

    Day 01 正课: 1.什么是DOM: 2.DOM Tree 3.遍历DOM树: 1.什么是DOM: 原生js=ECMAScript(核心语法)+ DOM(专门操作网页内容的API)+ 3天 BOM ...

  6. Lua 自定义函数string.split

    function string.split(str, delimiter)    if str==nil or str=='' or delimiter==nil then        return ...

  7. maven clean deploy -Pproduction

    今天我修改了公司的组件,要发布.然后腾飞告诉我用这个命令:clean deploy -Pproduction发布. 然后报了个401错误.(当时还是不知道401是什么错)正好经理在旁边问了一下,没想到 ...

  8. CentOS 7 安装 WordPress,PHP,Nginx,MySQL(MariaDB),FTP

    主要资料参考:https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-st ...

  9. 【POJ3621】Sightseeing Cows

    Sightseeing Cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8331   Accepted: 2791 ...

  10. Nginx-Lua模块的执行顺序

    一.nginx执行步骤 nginx在处理每一个用户请求时,都是按照若干个不同的阶段依次处理的,与配置文件上的顺序没有关系,详细内容可以阅读<深入理解nginx:模块开发与架构解析>这本书, ...