Java serialization mechanism Learning

Source: Internet
Author: User

What is serialization?
The serialization mechanism in Java can write the status information of an instance object to a byte stream, so that it can be transmitted through socket or stored persistently in a database or file system; then, you can reconstruct an object based on the information in the byte stream as needed. Serialization mechanism is widely used in Java, and EJB, RMI, and other technologies are based on this.

Correct use of serialization Mechanism
To serialize a class, you only need to implement java. Io. serializable interface. This interface is a markup interface that does not contain any content. If this interface is implemented, this class is ready to support serialization. The following example defines the class person and declares that it can be serialized.

Java code

1. Public class person implements java. Io. serializable {}

Public class person implements java. Io. serializable {}

The serialization mechanism is implemented through the java. Io. objectoutputstream class and Java. Io. objectinputstream class. When serialize is an object, an objectoutputstream object is first instantiated and Its writeobject () method is called. When deserializing (deserialize, an objectinputstream object is instantiated and Its readobject () method is called. The following example illustrates this process.
Java code

1. Public void serializeobject (){
2. String filename = "Ser. Out ";
3. fileoutputstream Fos = new fileoutputstream (filename );
4. objectoutputstream OOS = new objectoutputstream (FOS );
5. OOS. writeobject (new person ());
6. OOS. Flush ();
7 .}
8.
9. Public void deserializeobject (){
10. String filename = "Ser. Out ";
11. fileinputstream Fos = new fileinputstream (filename );
12. objectinputstream OOS = new objectinputstream (FOS );
13. Person P = OOS. readobject ();
14 .}

In the above example, we define serialization and deserialization operations for a person object. However, if the person class cannot be serialized, that is, the serialization operation on classes that cannot be serialized will throw a java. Io. notserializableexception.
JVM has a predefined serialization implementation mechanism, that is, objectoutputstream. defaultwriteobject () and objectinputstream. defaultreadobject () are called by default to execute the serialization operation. To customize the serialization implementation, you must implement the writeobject () and readobject () methods in the declared serializable class.

Usage
When serializing a class A, there are three situations:
# [List = 3] Class A has no parent class and implements the serializable interface.
# Class A has parent class B and the parent class implements the serializable Interface
# Class A has parent class B, but the parent class does not implement the serializable Interface
[/LIST]
In the first case, You can directly implement the serializable interface.
In the second case, because the parent class B has implemented the serializable interface, Class A does not need to implement this interface. If the parent class implements writeobject () and readobject (), this method is used. Otherwise, the default mechanism is used directly.
In the third case, the writeobject () and readobject () methods must be displayed in Class A to process the status information of the parent class B. Pay special attention to this, in parent class B, a constructor without parameters is required, because during deserialization, no constructor declared as serializable Class A is used, instead, it calls the non-argument constructor of its parent class B that is not declared as serializable.

Serialization mechanism problems
# [LIST] performance problems
To serialize An Instance Object of Class A, all information to be saved is as follows:
1. Metadata of all classes related to this instance object (metadata); because of the inheritance relationship, the Instance Object of Class A is also the object of any of its parent classes. Therefore, metadata information of each class on the entire inheritance chain needs to be saved in sequence from parent to child.
2. Description of Class. This description may contain the following information: Version ID of the class) indicates whether the flag of the serialization implementation mechanism is customized, the number of serializable attributes, the name and value of each attribute, and the description of its serializable parent class.
3. The instance object is used as each of its superclasses, and the data information is saved.
# In remote call applications such as RMI, each call to a method requires so much information. Over time, the system performance will be greatly affected. Version Information
When the readobject () method is used to read the byte stream information of a serialized object, the description information of all related classes and the status data of the sample object are obtained; then compare the description with the description of the class to be constructed locally. If the description is the same, a new instance is created and its status is restored. Otherwise, an exception is thrown. This is the version check of the serialized object. The default description information in JVM is represented by a long-integer hashcode value, which is related to various aspects of the class, such as class name, class modifier, implemented Interface Name, method and constructor information, and attribute information. Therefore, some minor changes to a class may lead to different hash values. For example, we start to serialize an instance object, add a method to the class, or change the name of an attribute. When we want to reconstruct the previous object based on the serialization information, at this time, the version information of the two classes does not match and the object cannot be restored. To solve this problem, a defined value may be displayed in the class, as shown below:
Java code

1. Private Static final long serialversionuid = alongvalue;

In this way, the serialization mechanism uses this value as the version identifier of the class to solve incompatibility issues. However, it introduces a new problem, even if a class changes substantially, such as adding or deleting some serializable attributes, in this mechanism, the two classes are still considered equal.
[/LIST]
A better choice
As an alternative to implementing the serializable interface, the Java. Io. externalizable interface can also identify a class as serializable.
The externalizable interface defines the following two methods:
Java code

1. Public void readexternal (objectinput in );
2. Public void writeexternal (objectoutput out );

The functions of these two methods are the same as those of the readobject () and writeobject () methods. Any class that implements the externalizable interface requires these two functions to define its serialization mechanism.
Externalizable is more efficient than serializable. The former serializes an object, the information to be saved is smaller than the latter, and the latter needs to save 3rd pieces of information, the former does not need to access each parent class and save relevant state information, but simply calls the writeexternal () method implemented in the class.

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.