What is the underlying implementation principle of serialization and deserialization?

Source: Internet
Author: User
Tags object serialization serialization thread class

Serialization and deserialization as a basic knowledge point in Java, we also have a few words to say, but I believe that a lot of small partners to grasp that is just a few words, if you dig deeper to ask how Java implementation of serialization and deserialization, you may be overwhelmed. I was asked this question in my mind confidently said a lot of, what is serialization, what is deserialization, what the time will be used to wait, and then the interviewer said: Then you can say the serialization and deserialization of the bottom is how to achieve it. A face, and then go home to wait for notice. I. Basic Concepts

1. What is serialization and deserialization

(1) Java serialization refers to the process of converting a Java object into a byte sequence, while Java deserialization refers to the process of restoring a byte sequence to a Java object;

(2) serialization: The most important use of object serialization is to ensure the integrity and transitivity of objects when they are passed and saved. Serialization is the conversion of an object into an ordered byte stream to be transmitted over a network or stored in a local file. The serialized byte stream saves the state of the Java object and related descriptive information. The core function of the serialization mechanism is the preservation and reconstruction of the object state.

(3) deserialization: When the client obtains the serialized object byte stream from the file or the network, the object is reconstructed by deserialization according to the state of the object and the description information saved in the byte stream.

(4) Essentially, serialization is to write the entity object State in a certain format to the ordered byte stream, and the deserialization is to reconstruct the object from the ordered byte stream and restore the object state.

2. Why serialization and deserialization are needed

We know that when two processes are communicating remotely, each type of data can be sent to each other, including text, pictures, audio, video, and so on, and the data is transmitted over the network in the form of a binary sequence.

So when two Java processes are communicating, can you implement object transfer between processes? The answer is yes. How to do it. This requires Java serialization and deserialization.

In other words, on the one hand, the sender needs to convert the Java object into a byte sequence and then send it over the network, on the other hand, the receiver needs to recover the Java object from the byte sequence.

When we understand why Java serialization and deserialization are needed, it is natural to think of the benefits of Java serialization. One of the benefits is the persistence of data , which can be permanently saved to the hard disk (usually in a file) by serialization, and the second is to use serialization to implement remote communication , that is, to transfer the byte sequence of objects over the network.

In general, it boils down to the following points:

(1) Permanently save the object, save the object's byte sequence to the local file or database;
(2) The object is transmitted and received in the network by means of serialization in the form of a byte stream;
(3) Passing objects between processes through serialization;

3, the serialization algorithm will generally follow the steps to do the following things:

(1) The output of the class metadata related to the object instance.
(2) Recursively output the superclass description of the class until there is no more superclass.
(3) After the class metadata is finished, start outputting the actual data value of the object instance from the topmost superclass.
(4) Recursive output from top to bottom data Two, Java How to achieve serialization and deserialization

1, the JDK Class library serialization and deserialization of the API

(1) Java.io.ObjectOutputStream: Representing the object output stream;

Its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting byte sequence to a target output stream;

(2) Java.io.ObjectInputStream: Represents an object input stream;

Its readobject () method reads the byte sequences in the source input stream, deserializes them into an object, and returns them;

2, to achieve the requirements of serialization

Only objects that implement the serializable or Externalizable interface can be serialized, otherwise an exception is thrown.

3, implementation of Java object serialization and deserialization method

Suppose a user class, whose objects need to be serialized, can have the following three methods:

(1) If the user class implements only the Serializable interface, it can be serialized and deserialized in the following ways

ObjectOutputStream uses the default serialization method to serialize the transient instance variables of the user object.
Objcetinputstream uses the default deserialization method to deserialize a transient instance variable of the user object.

(2) If the user class only implements the Serializable interface, and also defines ReadObject (ObjectInputStream in) and WriteObject (Objectoutputsteam out), Serialization and deserialization are done in the following ways.

ObjectOutputStream the method of calling the user object's WriteObject (ObjectOutputStream out) for serialization.
ObjectInputStream will call the ReadObject (ObjectInputStream in) method of the user object for deserialization.

(3) If the user class implements the Externalnalizable interface, and the user class must implement the Readexternal (ObjectInput in) and Writeexternal (ObjectOutput out) methods, Serialization and deserialization are done in the following manner.

ObjectOutputStream the method that invokes the Writeexternal (ObjectOutput out) of the user object.
ObjectInputStream will call the Readexternal (ObjectInput in) method of the user object for deserialization.

4. Steps for serialization in JDK class libraries

Step One: Create an object output stream that can wrap a different type of target output stream, such as a file output stream:

ObjectOutputStream oos = new ObjectOutputStream (New FileOutputStream ("D:\\object.out"));

Step two: Write the object through the WriteObject () method of the object output stream:

Oos.writeobject (New User ("Xuliugen", "123456", "male"));

5. Steps for deserializing in JDK class library

Step One: Create an object input stream that can wrap a different type of input stream, such as a file input stream:

ObjectInputStream ois= New ObjectInputStream (New FileInputStream ("Object.out"));

Step Two: Read the object through the ReadObject () method of the object output stream:

User user = (user) ois.readobject ();

Note: In order to read data correctly and to complete deserialization, it is necessary to ensure that the order of the object output stream writes to objects in the order of the objects being read from the object input stream.

6. Examples of serialization and deserialization

To better understand Java serialization and deserialization, a simple example is as follows:

public class Serialdemo {public

    static void Main (string[] args) throws IOException, ClassNotFoundException {
        //Preface nematic
        FileOutputStream fos = new FileOutputStream ("Object.out");
        ObjectOutputStream oos = new ObjectOutputStream (FOS);
        User User1 = new User ("Xuliugen", "123456", "male");
        Oos.writeobject (user1);
        Oos.flush ();
        Oos.close ();
        Deserialization of
        FileInputStream fis = new FileInputStream ("Object.out");
        ObjectInputStream ois = new ObjectInputStream (FIS);
        User User2 = (user) ois.readobject ();
        System.out.println (User2.getusername () + "" + 
            User2.getpassword () + "" + user2.getsex ());
        The output of deserialization is: Xuliugen 123456 male
    }} public

class User implements Serializable {
    private String UserName;
    private String password;
    Private String sex;
    Full-parameter constructor method, get and set method ellipsis
}

The Object.out file is as follows (open using UltraEdit):

Note: The 0000000h-000000c0h in the above image represents the line number; 0-f represents the column; the text at the end of the line indicates an explanation of the line 16; the content expressed in the above bytecode can be compared with the relevant information, and the meaning of each character is examined.

Similar to our Java code after the compilation of the. class file, each word characters represents a certain meaning. the process of serialization and deserialization is the process of generating and parsing these characters.

Serialization diagram:

Anti-serialization diagram:

Iii. related matters of concern

1. When serializing, only the state of the object is saved, regardless of the object's method;

2. When a parent class realizes serialization, the subclass is automatically serialized, and the serializable interface is not needed explicitly.

3. When an object's instance variable references another object, serializing the object also serializes the referenced object;

4, not all objects can be serialized, as for why not, there are many reasons, such as:

Security reasons, such as an object has private,public field, for a transmission of objects, such as writing to file, or RMI transmission, etc., in the process of serialization, the object's private domain is not protected;

Resource allocation reasons, such as the Socket,thread class, if they can be serialized, transmitted or saved, cannot be reallocated to their resources, and it is not necessary to achieve this;

5. member data declared as static and transient types cannot be serialized. Because static represents the state of a class, transient represents the temporary data for the object.

6. The serialization runtime uses a version number called Serialversionuid that is associated with each serializable class, which is used during deserialization to verify that the sender and receiver of the serialized object loaded the serialized compatible class for the object. Give it a definite value. There are two uses for explicitly defining SERIALVERSIONUID:

In some cases, you want different versions of your class to be compatible with serialization, so you need to ensure that different versions of the class have the same serialversionuid;

On some occasions, you do not want different versions of a class to be compatible with serialization, so you need to ensure that different versions of the class have different serialversionuid.

7, Java has a lot of basic classes have been implemented serializable interface, such as String,vector. But there are some that do not implement the Serializable interface;

8. If the member variable of an object is an object, then the data members of the object are also saved. This is an important reason for using serialization to solve deep copy.

See here, may have made us very satisfied, after all, we've learned how serialization and deserialization we use at ordinary times is what we do, what Java provides us with what interfaces are available, and how much more than what we initially knew was serialization, deserialization, and function. We will continue to discuss and update the following content.

Reference articles:

1, https://zhidao.baidu.com/question/688891250408618484.html
2, https://blog.csdn.net/morethinkmoretry/article/details/5929345
3, https://www.jianshu.com/p/edcf7bd2c085
4, https://blog.csdn.net/xiaocaidexuexibiji/article/details/22692097

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.