interviewer : brother , Tell me what you think of me transient Understanding and perception of

Su xiaonuan :what? There is also sentiment ?

One , Basic concepts

1, Serialization and deserialization definitions

Java Serialization refers to serialization Java Object to a sequence of bytes .

Java Deserialization is to restore a sequence of bytes to Java Object process .

2, The role of serialization and deserialization

(1) Serialization

When passing and saving objects , Preserve the integrity and transitivity of objects .
Object to an ordered byte stream , It can be transferred over the network or saved locally ( commonly json/xml Most documents ) in .

(2) Deserialization effect

According to the object state and description information saved in the byte stream , Rebuilding objects by deserialization .

Two , Advantages and disadvantages of serialization and deserialization

1, advantage

(1) Convert the object into a byte stream and store it on the hard disk , When JVM When it stops , The byte stream also waits on the hard disk , Wait for the next time JVM start-up , To serialize an object , Convert to the original object by deserialization , And the serialized binary sequence can reduce the storage space ( Permanently save objects ).

(2) Objects serialized as byte stream can be transmitted over the network ( Binary form ).

(3) Objects can be passed between processes through serialization .

2, shortcoming

(1) Cannot cross language

Can't cross language Java The most fatal problem of serialization .

For cross process service invocation , The service provider may be Java Languages other than English , When we need to interact with other languages ,Java Serialization is not up to it .

in fact , At present, almost all popular Java RPC Communication framework , None of them were used Java Serialization as an encoding and decoding framework , The reason is that it can't cross language , And these RPC Frameworks often need to support cross language calls .

 Java RPC Introduction of communication framework

RPC Is short for remote procedure call , Widely used in large-scale distributed applications , The function is to facilitate the vertical splitting of the system , Make the system easier to expand .Java in RPC There are many frameworks , Each has its own characteristics , Widely used are RMI,Hession,Dubbo etc .

1,RMI( Remote method call ):

JAVA Built in remote method calling tool , But there are some limitations , After all, it is JAVA Design at the beginning of language , Later, the principles of many frameworks were based on RMI.

2,Hessian( be based on HTTP Remote method call for ):

be based on HTTP Protocol transfer , It's not perfect in terms of performance , Load balancing and fail over depend on the load balancer of the application ,Hessian The use of this method is different from that of traditional Chinese medicine RMI similar , The difference is that it's diluted Registry The role of , Call through the displayed address , utilize HessianProxyFactory According to the configured address create A proxy object , In addition, we need to introduce Hessian Of Jar package .

3,Dubbo( Taobao open source based on TCP Of RPC frame )

Dubbo It's a high performance car , Lightweight open source Java RPC frame , It provides three core competencies : Interface oriented remote method call , Intelligent fault tolerance and load balancing , And automatic service registration and discovery .

(2) The length of the stream after serialization is much larger than that through buffer processing .

<>(3) Serialization performance is too low

Three , Serializing usage scenarios

1, Distributed delivery object , Or network transmission , Serialization required

2, I call your jvm How to do it , The results are returned to my jvm To deal with the problem

3, Serialization preserves the state of an object
such as :tomcat After closing, it will session Object serialized to SESSIONS.ser In the file , Let's get these started next time session Then load it into memory .

4, Data transmission and recovery

stay j2ee Page and background use more . Especially when it is used in the list .

such as : If a list of people is saved , You can serialize this list , Get it backstage , And then reverse sequenced into person Object directly saves the object .

5, such as EJB Remote call   Distributed storage , Cache storage, etc

6, Like a bank card , Password these fields cannot be serialized

Four , Considerations for serialization and deserialization

1,Java How to serialize

realization Serializable Interface : It can be customized writeObject,readObject,writeReplace,readResolve
method , Is called by reflection .

realization Externalizable Interface : Need to achieve writeExternal and readExternal method .

2, serialize ID problem

Does the virtual machine allow deserialization , Not only depends on whether the class path and function code are consistent , A very important point is the serialization of two classes ID Is it consistent ( namely private static
final long serialVersionUID = 1L).

3, Static fields are not serialized

Static variables are not saved when serializing , This is because serialization saves the state of the object , Static variables belong to the state of the class , Therefore, serialization does not save static variables .


transient Temporary data representing an object .

If you don't want a member of an object to be serialized, you can add it when you define it transient Keyword , such , When an object is serialized, it is not serialized .

transient The modified member will be given a default value after deserialization , Namely 0 or null.

Sometimes, fields like bank card number don't want to be transmitted on the network ,transient The function of this field is to save the life cycle of this field only in the memory of the caller and not write it to the disk for persistence .

5, Serialization of parent class

When a parent class implements serialization , Automatic serialization of subclasses ; The subclass implements the Serializable Interface , The parent class also needs to be implemented Serializable Interface .

6, When an instance variable of an object refers to another object , The reference object is also serialized when the object is serialized

7, Not all objects can be serialized

(1) Safety reasons , For example, an object has private,public etc. field, For an object to be transferred , Like writing to a file , Or do it RMI Transmission and so on , During the transmission of serialization , This object's private Equal fields are not protected ;

(2) Reasons for resource allocation , such as socket,thread class , If serializable , To transmit or save , There's no way to reallocate them , and , There is no need to achieve this ;

8, Serialization solves deep copy problem

If the member variable of an object is an object , Then the data members of this object will also be saved , This is an important reason why deep copy can be solved by serialization .

Five , Code instance

1, Entity class
package javase.transientpackage; import; public class
User implements Serializable { private static final long serialVersionUID = 1L;
private String username; private transient String password;
//construct,setter,getter }
2,ObjectOutputStream Implement serialization and ObjectInputStream Implement deserialization  
package javase.transientpackage; import*; public class TransientTest
{ public static void main(String[] args) { try { SerializeUser();
DeSerializeUser(); } catch (IOException e) { e.printStackTrace(); }catch
(ClassNotFoundException e) { e.printStackTrace(); } } // serialize private static void
SerializeUser() throws IOException{ User user = new User();
user.setUsername(" Su xiaonuan "); user.setPassword("123456"); ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("D://data.txt"));
oos.writeObject(user); oos.close(); System.out.println(" Normal field serialization :username=
"+user.getUsername()); System.out.println(" Added transient Keyword serialization :password=
"+user.getPassword()); } // Deserialization private static void DeSerializeUser() throws
IOException, ClassNotFoundException { File file = new File("D://data.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); User
user = (User)ois.readObject(); System.out.println(" Normal field deserialization :username=
"+user.getUsername()); System.out.println(" Added transient Keyword deserialization :password=
"+user.getPassword()); } }
3, console output

©2019-2020 Toolsou All rights reserved,
Unity Scene loading asynchronously ( Implementation of loading interface )ESP8266/ESP32 System : Optimize system startup time vue Of v-if And v-show The difference between JS How to operate college examination for the self-taught An overview of Marxism Faster RCNN Explanation of series algorithm principle ( note )CSS architecture design NOI2019 travels IAR Installation and use tutorial sort ( one ) bubble sort