In-depth analysis of Java serialization

Source: Internet
Author: User

Concept

Let's start with some simple concepts:
what?why?
What is serialization? Why serialize?
Answer: Convert the Java object into a sequence of bytes for transmission and saving
where?
What is the usage scenario?
Answer: The transfer of the object, the state of the backup, such as the JVM dump file;
All right, no, no, it's a little more detailed. In fact, the serialization of objects has two main purposes:

    • Permanently saves the byte sequence of an object to the hard disk, usually in a file
    • A sequence of bytes that transmit an object over the network

In many applications, some objects need to be serialized to leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be unbearable, so the Web container will be some seesion first serialized to the hard disk, and so on, Restore the objects that were saved to the hard disk in memory.
When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.

Implementation method

How?

    1. (classes that require serialization) implement the Serializable interface. See the source serializable is an empty interface (there is no method), that is, labeled interface. The role is to explicitly tell Java, this class needs to serialize, do not implement this interface, the object is not able to serialize and transmit (if not add implements Serializable, will error, suggest try, intuitive feeling), similar to the marking interface and cloneable.
    2. Creates an input-output stream. First, to serialize an object, you need to create some outputstream (such as FileOutputStream, Bytearrayoutputstream, and so on), These outputstream are then encapsulated in a objectoutputstream. At this point, you simply call the WriteObject () method to serialize the object and send it to OutputStream (the object's serialization is byte-based and cannot use a character-based hierarchy such as reader and writer). Second, the process of deserializing (reverting a sequence to an object) requires that a inputstream (such as FileInputStream, Bytearrayinputstream, and so on) be encapsulated within the ObjectInputStream. Then call ReadObject (). In simple terms:
      Serialization: Objectoutputstream.writeobject (Object)
      Deserialization: Objectinputstream.readobject ()

See the following example:
First define an object to serialize:

 PackageCom.alibaba.serialize.common;Importjava.io.Serializable;/ * * Do not add implements Serializable, will error * * Public  class User implements Serializable{    Private Static Final LongSerialversionuid =1LPrivateString username;Private intAge Public User(String username,intAge) { This. Username = Username; This. Age = Age; } PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }}

Write another example of serialization

 PackageCom.alibaba.serialize.common;ImportJava.io.BufferedOutputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.ObjectOutputStream; Public  class serializeexample {     Public Static FinalString Out_file ="Src/com/alibaba/serialize/temp.out"; Public Static void Main(string[] args) {User User =NewUser ("Tony", -);Try{//If this is changed to a network output stream instead of a file output stream (deserialization is also changed to a network input stream), it can be transmitted over the networkObjectOutputStream out =NewObjectOutputStream (NewBufferedoutputstream (NewFileOutputStream (Out_file)); Out.writeobject ("User information:");            Out.writeobject (user);        Out.close (); }Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); } System.out.println ("Serialization is complete. Please call the deserialization class Deserializeexample to complete the deserialization! "); }}

Finally, write an example of deserialization

 PackageCom.alibaba.serialize.common;ImportJava.io.BufferedInputStream;ImportJava.io.FileInputStream;ImportJava.io.ObjectInputStream; Public  class deserializeexample {     Public Static void Main(string[] args)throwsexception{ObjectInputStream in =NewObjectInputStream (NewBufferedinputstream (NewFileInputStream (Serializeexample.out_file));            string title = (string) in.readobject ();            System.out.println (title);            User user = (user) in.readobject (); System.out.println ("User name:"+user.getusername ()); System.out.println ("User age:"+user.getage ()); }}

Run separately SerializeExample and DeserializeExample you can see the corresponding effect.

Serialized file Relationships

Say a few things that are usually overlooked.

    1. If a class does not implement the Serializable interface, but its base class is implemented, the class can also be serialized;
    2. Conversely, if a class implements the Serializable interface, but its parent class is not implemented, the class can still be serialized (object is the parent of all classes), but the subclass object is serialized, and then the value of a variable that is defined by the parent class is output after deserialization. It will be found that the value of the variable is different from the value of the serialization (generally null or other default values), and the parent must have an argument-free construction method, or the subclass will be deserialized when the error.

See Example:
Write a parent class first

 PackageCom.alibaba.serialize.parent;Importjava.io.Serializable; Public  class carserialize{    PrivateString name;PrivateLong Price;/ * No this parameterless constructor will error, can be deleted, tested under */     Public carserialize() {Super(); } Public carserialize(String name, Long price) { This. name = name; This. Price = Price; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicLongGetPrice() {returnPrice } Public void Setprice(Long Price) { This. Price = Price; }}

Write the sub-class again

 PackageCom.alibaba.serialize.parent;Importjava.io.Serializable; Public  class bmwserialize extends carserialize  implements  Serializable{    PrivateString name;PrivateLong Price; Public bmwserialize(String name, Long price) {Super(name, price); } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicLongGetPrice() {returnPrice } Public void Setprice(Long Price) { This. Price = Price; }   }

Finally write a test class

 PackageCom.alibaba.serialize.parent;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream; Public  class serializetest {     Public Static void Main(string[] args) {Try{ObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("Result.obj")); Out.writeobject (NewBmwserialize ("BMW", -L));            Out.close (); ObjectInputStream oin =NewObjectInputStream (NewFileInputStream ("Result.obj"));            Bmwserialize BMW = (bmwserialize) oin.readobject (); System.out.println ("decrypted string:"+ Bmw.getname ());        Oin.close (); }Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); }Catch(ClassNotFoundException e)        {E.printstacktrace (); }    }}

In the above code, you can try to test according to the two points I said above.

There's one more place to watch.
The object reference relationships of the same stream are well preserved, and the object reference relationships of the different streams cannot guarantee matching
This point I feel more easy to understand, do not write, there is time to test.

Serialization ID

Think of a question: what happens if the two ends or versions are different after serialization, class is inconsistent?

???
???

Here is the concept of the serialization ID , Serialversionuid for the Java serialization mechanism. When deserializing, the constructor and assignment statements do not take effect if the class changes.

In simple terms, the serialization mechanism of Java is to verify version consistency by judging the serialversionuid of the class. When deserializing, the JVM compares the serialversionuid in the stream to the serialversionuid of the local corresponding entity class, and if the same is considered consistent, it can be deserialized, otherwise the serialized version inconsistency exception will occur. That is InvalidCastException (as in the previous section, when you delete the parameterless constructor of the parent class, the deserialization will also report the error).

Serialversionuid There are two ways to generate the display:

    • One is the default 1L, for example: private static final long Serialversionuid = 1L
    • The second is to generate a 64-bit hash field based on the class name, interface name, member method, and property, for example:private static final long serialVersionUID = xxxxL;

Consider another question, if the serialization ID is the same, assuming that the A-side is serialized, the B-side is deserialized, and the B-end serialization object changes before deserialization, there are several cases? In fact, the logic is still relatively easy to understand, slightly summed up below, roughly the following:

    • B Plus field: serialization, deserialization normal, B end the newly added int field is given the default value for the field type (such as 0 or false)
    • B-Delete field: serialization, deserialization normal (no error), B-end field less than a end, a-end field value is missing
Custom serialization

Since the topic is in-depth analysis, that of course to continue to analyze, haha ~ So, ask another question, when the object has sensitive fields to do? such as password. Can you decide how to serialize? Explain here.

During serialization, the virtual opportunity attempts to invoke the WriteObject and ReadObject methods in the object class for user-defined serialization and deserialization, and if there is no such method, the default call is ObjectOutputStream Defaultwriteobject method and the Defaultreadobject method of ObjectInputStream. The user-defined WriteObject and ReadObject methods allow the user to control the serialization process, such as the ability to dynamically change the serialized value during serialization.

Based on this principle, it can be used in practical applications, for cryptographic work of sensitive fields, see examples (code from resources).
First write a custom serialization process for the object to be serialized.

 PackageCom.alibaba.serialize.customer;ImportJava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectInputStream.GetField;ImportJava.io.ObjectOutputStream;ImportJava.io.ObjectOutputStream.PutField;Importjava.io.Serializable; Public  class securityinfo implements Serializable{    PrivateString Password ="Pass"; PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; }Private void writeobject(ObjectOutputStream out) {Try{Putfield putfields = Out.putfields (); System.out.println ("Original password:"+ password); Password ="Encryption";//Analog encryptionPutfields.put ("Password", password); System.out.println ("Password after encryption"+ password);        Out.writefields (); }Catch(IOException e)        {E.printstacktrace (); }    }Private void ReadObject(ObjectInputStream in) {Try{GetField readfields = In.readfields (); Object object = Readfields.get ("Password",""); System.out.println ("string to decrypt:"+ object.tostring ()); Password ="Pass";//analog decryption, need to get local key}Catch(IOException e)        {E.printstacktrace (); }Catch(ClassNotFoundException e)        {E.printstacktrace (); }    }}

Write a test class again

 PackageCom.alibaba.serialize.customer;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream; Public  class customerserialize {     Public Static void Main(string[] args) {Try{ObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("Result.obj")); Out.writeobject (NewSecurityinfo ());            Out.close (); ObjectInputStream oin =NewObjectInputStream (NewFileInputStream ("Result.obj"));            Securityinfo t = (securityinfo) oin.readobject (); System.out.println ("decrypted string:"+ T.getpassword ());        Oin.close (); }Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); }Catch(ClassNotFoundException e)        {E.printstacktrace (); }    }}

Ok! Let's run it down.
In fact, when it comes to custom serialization, there are two ways to implement a externalizable interface by implementing the Java serialization of another interface Externalizable, as follows:

Roughly summed up the difference between externalizable and serializable:

implementing the Serializable interface Implement Externalizable
The system automatically stores the necessary information What information the programmer decides to store
Java built-in support, easy to implement, just implement the interface, without any code support Only two empty methods are provided, implementing the interface must provide an implementation for two empty methods
Slightly worse performance Slightly higher performance

In fact, although externalizable performance is high, but we generally rarely see in the code, this reason needs to leave someone else, personally think it may be their own writing is not enough general, too troublesome, and generally sensitive information will not be so transmitted.

Comparison of several serialization protocols

Here we introduce and compare several of the more popular serialization protocols, including XML, JSON, PROTOBUF, Thrift, and Avro. Because I don't use much of it here, only JSON and XML are used, so here's a reference for comparison: http://tech.meituan.com/serialization_vs_deserialization.html

This article also refers to:
http://blog.csdn.net/zhaozheng7758/article/details/7820018

Thanks to the above author ~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

In-depth analysis of Java serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.