Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Serialization

• When you create a class, you may create an object for that particular class
and once we execute/terminate the program, the object is destroyed by
itself (Garbage Collector thread). What happens if you want to call that
class without re-creating the object. In those cases what you do is that, we
use the serialization concept by convert data into byte stream.
Definition
Object Serialization is a process used to convert
state of an object into byte stream which can
be persisted into disk/file or sent over network
to any other running Java virtual machine;
and the reverse process of creating object from
byte stream is called deserialization in Java.
The byte stream created is platform
independent. So, the object serialized on one
platform can be deserialized on a different
platform.
Why do we need serialization?
There are following reasons:
1. Communication
2. Persistency
3. Deep copy
4. Caching
5. Cross JVM synchronization
How do we serialized
an object?
How to make a java class Serializable
Serializability can be enabled of your java class
by implementing the java.io.Serializable
interface.
It is a marker interface that means it contains
no methods or fields and only serves to identify
the semantics of being serializable.
Advantages of serialization:
• serialization process is a built-in feature that does not
require third-party software to execute Serialization
• The Serialization procedure is proven to
be simple and easy to understand
• Serialization procedure is universal and developers
from different background are familiar to it
• It is easy to use and simple to customize
• Serialized data streams support Encryption,
Compression, Authentication and secure Java
computing
• There are many critical technologies relying on
serialization
Disadvantages of serialization:
• Objects while De-Serialization becomes brittle and they are not
sure to be De-Serialized effectively.
• The Transient variables declared while Serialization creates
memory space, but the constructor is not called which results in
the failure in the initialization of transient variables resulting in
a variation to the Standard Java Flow.
• The process of serialization is inefficient in terms of memory
utilization.
• Serialization is not preferable to be used in the applications which
need concurrent access without the requirement of third-party
APIs, as Serialization does not offer any transition control
mechanism per every SE.
• Serialization procedure fails to offer fine-grained control to access
Objects.
What if we are trying to serialize a
non-serializable object?
• We will get RuntimeException saying :
Exception in thread "main"
java.io.NotSerializableException:
java.io.ObjectOutputStream
What is serialVersionUID ?
• SerialVersionUID is an ID which is stamped on object when
it get serialized usually hashcode of object. We can find
serialVersionUID for the object by serialver tool of java.
• SerialVersionUID is used for version control of object.
Consequence of not specifying serialVersionUID is that
when you add or modify any field in class then already
serialized class will not be able to recover because
serialVersionUID generated for new class and for old
serialized object will be different. Java serialization process
relies on correct serialVersionUID for recovering state of
serialized object and throws java.io.InvalidClassException in
case of serialVersionUID mismatch.
transient keyword :
• transient modifier/keyword applicable only
for variables but not for methods and classes.
At the time of serialization if we don't want to
serialize the value of a particular variable to
meet security constraints then we should
declare that variable as transient. While
performing serialization JVM ignores original
value of transient variable and save default
value to the file. Hence transient means not to
serialize
Example:
• Employee.java
import java.io.Serializable;
public class Employee implements Serializable { private static final long
serialVersionUID = 4676072847340124979L;
private int id;
private String name;
public Employee(int id, String name) {
super(); this.id = id; this.name = name; }
public int getId() {
return id; }
public void setId(int id) {
this.id = id; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name; } }
Serialization.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import
java.io.ObjectOutputStream;
public class Serialization {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Serialization serialization = new Serialization();
serialization.writeEmployeeObject(); }
private void writeEmployeeObject() throws FileNotFoundException, IOException { FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null; try {
fileOutputStream = new FileOutputStream("employee.ser");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
Employee employee = new Employee(101, "Peter");
/* * Write the specified object to the * ObjectOutputStream. */ objectOutputStream.writeObject(employee);
System.out .println("Successfully written employee object to the file.\n"); }
finally { if (objectOutputStream != null)
{ /* * Closing a ObjectOutputStream will also * close the OutputStream instance to which * the ObjectOutputStream is writing. */
objectOutputStream.close(); } } } }
output
• Successfully written employee object to the file.
Deserialization
• import java.io.FileInputStream;
• import java.io.FileNotFoundException;
• import java.io.IOException;
• import java.io.ObjectInputStream;
• public class DeSerialization { public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
• DeSerialization deSerialization = new DeSerialization(); deSerialization.readEmployeeObject(); }
• private void readEmployeeObject() throws IOException, FileNotFoundException,
ClassNotFoundException {
• FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null;
• try { fileInputStream = new FileInputStream("employee.ser");
• objectInputStream = new ObjectInputStream(fileInputStream);
• /* * Read an object from the ObjectInputStream.
• */ Employee employee = (Employee) objectInputStream.readObject(); System.out
.println("Successfully read employee object from the file.\n"); System.out.println("Id = " +
employee.getId());
• System.out.println("Name = " + employee.getName()); } finally { if (objectInputStream != null) {
• /* * Closing a ObjectInputStream will also * close the InputStream instance from which * the
ObjectInputStream is reading. */
• objectInputStream.close(); } } } }
Output
• Successfully read employee object from the
file.
• Id = 101
• Name = Peter

You might also like