Java serialization, deserialization, and Singleton mode

Source: Internet
Author: User

When we learn Java, especially when it comes to network programming, we often let our entity classes implement an interface

 Public class Implements serializable{}

This way we can write or read the object through the input output stream objectoutputstream and ObjectInputStream. So, simply put, serialization is the conversion of an object into a byte stream, and deserialization is the flow of a sequence of bytes into a corresponding Java object. The two most common scenarios used for serialization are:

1, need to store the object information in the disk file, such as a large number of user logon session information

2, need to transfer the object information through the network, the need to transmit the byte stream

After implementing the Java.io.Serializable interface, the editor gives a warning that you can define a property:

Private Static Final long serialversionuid = 1L;

We can simply assume that this is a "class version" of the representation, different editors may give different values for the same class, small changes to the class file may also produce different values, because this value after the class changes to play the role of code compatibility, the general rule is as follows:

1, two different versions of the class, if the Serialversionuid is the same, the deserialization is compatible, the existing version of the template is deserialized

2, two different versions of the class, if the Serialversionuid is different, indicating that deserialization is incompatible, deserialization will fail

Therefore, in our development process, it is recommended to display the value defined and give a clear definition to facilitate compatibility judgments.

The following code example first defines a serializable entity object:

 Packagecom.minlz.serialize;Importjava.io.Serializable;/** *  @authorMinliangzhi * @date August 30, 2016*/ Public classPersonImplementsSerializable {Private Static Final LongSerialversionuid = 20160830001L; PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; } @Override PublicString toString () {return"Person [name=" + name + ", age=" + Age + "]"; }}

A method for serializing and deserializing is then given:

     Public Static voidMain (string[] args)throwsException {person P1=NewPerson (); P1.setname ("Bruce Min"); P1.setage (25); System.out.println ("P1:" +p1.tostring ()); /**Serialization of*/Bytearrayoutputstream byteout=NewBytearrayoutputstream (); ObjectOutputStream objout=NewObjectOutputStream (byteout);                Objout.writeobject (p1); /**deserialization*/Bytearrayinputstream Bytein=NewBytearrayinputstream (Byteout.tobytearray ()); ObjectInputStream Objin=NewObjectInputStream (Bytein); Person P2=(person) objin.readobject (); System.out.println ("P2:" +p2.tostring ()); }

The results shown are:

P1:person [Name=bruce min, age=25]p2:person [name=bruce min, age=25]

Through the above example, it is possible to introduce serialization and deserialization, it is important to note that by deserializing the object is not the original object, that is, the "= =" is not true, because, if we are serializing a singleton instance, it will violate the rules of the singleton mode (although the single example of the constructor is hidden, But the JVM can construct objects by special means, such as reflection. Examples are as follows:

Singleton class:

 Packagecom.minlz.serialize;Importjava.io.Serializable;/** *  @authorMinliangzhi * @date August 30, 2016*/ Public classSingletonImplementsSerializable {Private Static Final LongSerialversionuid = 1L; Private StaticSingleton Singleton; PrivateSingleton () {} Public synchronized StaticSingleton getinstance () {if(NULL==Singleton) {Singleton=NewSingleton (); }                returnSingleton; }}

Serialization and deserialization of code:

     Public Static voidMain (string[] args)throwsException {Singleton S1=singleton.getinstance ();        System.out.println (S1); /**Serialization of*/Bytearrayoutputstream byteout=NewBytearrayoutputstream (); ObjectOutputStream objout=NewObjectOutputStream (byteout);                Objout.writeobject (S1); /**deserialization*/Bytearrayinputstream Bytein=NewBytearrayinputstream (Byteout.tobytearray ()); ObjectInputStream Objin=NewObjectInputStream (Bytein); Singleton S2=(Singleton) objin.readobject ();  SYSTEM.OUT.PRINTLN (S2); }

Test results:

[Email protected] [Email protected]

It is easy to see that two objects are not the same object, what is the workaround?

We add a method to the Singleton class:

     Public Object readresolve () {        return  getinstance ();    }

The test results were found to be:

[Email protected] [Email protected]

Two objects are consistent, so when faced with a singleton pattern instantiation, the public object Readresolve () method needs to be implemented, and a singleton instance can be returned to achieve the same serialization and deserialization.

Java serialization, deserialization, and Singleton mode

Related Article

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.