Monday, March 5, 2018

Serialization

Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.(https://www.geeksforgeeks.org/serialization-in-java/)

TALK-01

Short story about serialization
After many years of hard work, Earth's scientists developed a robot who can help them in daily work. But this robot had fewer features than the robots developed by the scientists from planet Mars.
After a meeting between both planets' scientists, it is decided that Mars will send their robots to Earth. But a problem occurred. The cost of sending 100 robots to Earth was $100 million. And it takes around 60 days of traveling.
Finally, Mar's scientists decided to share their secret with Earth's scientists. This secret was about the structure of class/robot. Earth's scientists developed the same structure on Earth itself. Mar's scientists serialized the data of each robot and sent it to earth. Earth's scientists deserialized the data and fed it into each robot accordingly.
This process saved them time in communicating a massive amount of data.
Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that the transient property is set to null (in case of reference) or to the default value (in case of the primitive type) when the object gets deserialized.
One more point noticed by Earth's scientists is that Mars's scientists asked them to create some static variables to keep details about the environment. These details are used by some robots. But Mars's scientists don't share these details. Because Earth's environment was different from Mars' environment.
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything started working.
TALK-02

Serialization is usually used When the need arises to send your data over network or stored in files. By data I mean objects and not text.
Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not JAVA objects.
Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.

This is analogous to how your voice is transmitted over PSTN telephone lines.


No comments:

Post a Comment