Learn Object Serialization in Java in Quick and Easy Manner in 25 Minutes

digitization, transformation, binary

Object Serialization in Java

Let us assume that we have drawn a picture on applet paint(2D graphics programming) and the picture became so sexy and cool, we want to save the paint to use further.

It is a common pain for everybody that if we close the Applet the picture will be gone. So what will do to protect our picture??

Ads code goes here

Again let us say we are playing a game and after sometimes I want to quite that for some other work. Now when I start the game again, It will start from the beginning. I want to save it in its current position.

Let’s take another case, where we have three objects in our program during run time. It means three objects are stored in memory. This memory management is done by JVM. Now out of these three objects, I might need the second one with the current state in my program at some other time or next time. How to use it??

If we close the program the object will be garbage collected. The memory will be freed. What could be the solution to protect my required object? How can I make use of the power of java to use reusable objects??
One more problem could be if the programmer wants to use an object in remote, and if both are in the same virtual space, it is easy to use that object by using a call by reference. If they are in different virtual spaces?? You have only one option left that is called by value.
Now let’s come to the point..how to save the applet paint??

There are two ways:-

  1. Do all the steps, you have done till now i.e redo, all the steps to get it back-No-this not good solution.99%chances are there, to forget what step we have done previously.
  2. Simple, hibernate your machine so that JVM continues to run. Yes, it is a good solution not always the best.

What is the catch from the above discussion??
Yes, you get it right!! The dots are:-
   (i)create an object.
   (ii)Allocate the memory but do not free space while closing the main process.
   (iii)Make sure your JVM runs to see the pic.
So, at any point in time if we can connect the three dots we can get the required paint/object, isn’t it??

The serializable interface in Java

the serializable interface defines no methods or constants. A class should implement this interface simply to indicate that it allows itself to be serialized and deserialized with objectOutputStream.writeObject() and ObjectInputStream.readObject().

Objects that need special handling during serialization or deserialization may implement one or both of the following methods. Note, however, that these methods are not part of the Serializable interface:

private void writeObject (java.io.ObjectOutputStream out) throws IOException
private void readObject (java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

Typically the writeObject() method performs any necessary cleanup or preparation for serialization, invokes the defaultWriteObject() method of the ObjectOutputStream to serialize the non-transient fields of the class, and then optionally writes any additional data that are required.

READ  Super Keyword in Java Simplified

Similarly, the readObject() method typically invokes the defaultReadObject() method of the ObjectInputStream, reads any additional data written by the corresponding writeObject() method, and finally performs any extra initialization required by the object.

The readObject()method may also register an ObjectInputValidation object to validate the object once it is completely deserialized.

Serializable interface

The Serializable interface is implemented by classes that allow object instances to be serialized and deserialized. A class uses the default serialization mechanism simply by implementing this interface. A class that wants finer control over serialization and deserialization should implement the following methods (with these exact signatures):

private void readObject(ObjectInputStream in) throws IOException,ClassNotFoundException;
private void writeObject(ObjectOutputStream out) throws IOException;

The ObjectOutputStream and ObjectInputStream classes support serialization and
deserialization, respectively.

The interface Structure of the Serializable is given as

public abstract interface java.io.Serializable {}

What Serialization offers??
Serialization offers to connect the dots. It saves the object and its current state. How ?? let see…

Serialization creates a stream of byte for an object and its state. Finally, when you create a file, object and save the serialization object it stores the stream of bytes to file, memory buffer or can be transmitted over the network.

Serialization also offers a strong API that will help you to create the sequence of a byte stream.
How it can be implemented??
Cool!! Now we need to serialize the object.
To serialize an object depicts:

  1. Converts an object and its state to a byte stream.
  2. This byte stream can be saved to a memory location or a storage-i.e file.
  3. The extension of the file may be “.ser”.
  4. The .ser file is machine-readable, not human-readable.
  5. The stored file should not be altered or if so JVM should not process it.
  6. The .ser file should be readable by JVM when configured.

For the first rule, we must implement a java.io.serialization interface.
So, the definition or signature of the class will be public class myClass implements serializable.

Well, java has come up with something that will connect these dots. That is object serialization. By this technique, one can save the application and load the state, where it was getting saved.

Somebody might ask why not a normal save. why this?

Serialization in java
Serialization in java

Well, the answer is very easy, the safe operation needs more attention-say your application and object state requires more byte of data than you thought of while starting your program. So every time you modify your application, it requires to update the specification of the storage medium, secondly, you need to configure save and again restore mechanism.

Advantages of Serialization

  1. Reduced time to write code for saving and retrieve the object and its state.
  2. As it is giving a new file format it reduces the complexity of such coding.
  3. Reusable objects, when converted to a stream of byte, can move any location without a problem.
  4. While working with remote objects, when we want to re-reference to the remote object, if both are in the same virtual space, they can talk by reference but when they are on different virtual spaces..well, this time you need to invoke pass by value and serialization.
  5. Easy API for serialization.
READ  Class Observable in Java

Disadvantages of Serialization:-

  • Java Serialization is an expensive operation in terms of large output byte file.
  • It might affect performance.
  • Easy to get corrupted.
  • caching objects in the stream needs to be implemented very carefully.
OutputStream out=new objectOutputStream();
myObject obj=new myObject();
obj.setstrate(100);
out.writeObject(100);
obj.SetStrate(200);
out.WriteObject(200);

This is not saved. To set another value, we need to close outputStream and open again.

  • While overwriting an object/class, this may throw a java.io.InvalidClassExcaption.
  • Serialization works for only public constructors, so there may be a security threat that anybody can access that class.
  • It is a bit slow and the backend technique is kind of known to the user.

In Serialization, we convert an “in memory” object to a byte stream. This byte stream, when saved to a file, is not readable to the user. This process is also called deflating or marshaling an object.
There are three different ways so that we can implement serialization testing:-

  • default protocol
  • Customized default protocol
  • Own protocol

I wanted to save [email protected] time: Wed Feb 01 16:56:45 IST 2012
This is what I got in the file
Ԁ牳ༀ牰橯捥ㅴ洮呹浩깥좟ʜĀL琄浩瑥က橌癡⽡瑵汩䐯瑡㭥灸牳฀慪慶甮楴⹬慄整橨Ɓ奋ᥴ 砀睰 Ā㠵뎪碈
I am going to write the practice code to get an object and its state serialized. And again we are going to read that. Time is a serializable object, so we will work on Time.
My object is to capture the current time and save it to a file. Again read from that file.

For capturing time we need to create a class. This is a separate class that will tell java that this class’s object is serializable. So we use to implement that class to Serializable.

import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
public class myTime implements Serializable {
private Date time;
public myTime() {
time=Calendar.getInstance().getTime();
}
public Date callTime() {
return time;
}
public static void main(String[] args) {
myTime myTime = new myTime();
}
}

Cool …The second objective is to create a class that will create a file and writes this time as a serialized object. I am going to create a file called time. ser under C drive.
There are two things important here

  • FileOutputStream
  • ObjectOutputStream

 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class writeData {
    public static void main(String[] args) {
    String fileName="time.ser";
    FileOutputStream fos=null;
    ObjectOutputStream out=null;
    myTime time=new myTime();
    try{
        File file;
        file = new File("C:\"+fileName);
        fos=new FileOutputStream(file);
        out=new ObjectOutputStream(fos);
        out.writeObject(time);
        out.close();
        fos.close();
    } catch (FileNotFoundException e) {
       // TODO
    }
    catch (IOException e) {
      // TODO
    }
    }
}

if I compile and run this program, I am going to get a file created under C drive called time.ser.This file is the container where the serialized object is placed. This is not readable by humans. Only JVM can read this file. It is strongly advisable that please do not open or modify the file
This file contains a line like—
Ԁ牳ༀ牰橯捥ㅴ洮呹浩깥좟ʜĀL琄浩瑥က橌癡⽡瑵汩䐯瑡㭥灸牳฀慪慶甮楴⹬慄整橨Ɓ奋ᥴ 砀睰 Ā㠵뎪碈
Now we need to read it…

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;
public class readData {
    public static void main(String[] args) {
        String filename = "time.ser";
        myTime time = null;
        FileInputStream fis = null;
        ObjectInputStream in = null;
        try
        {
        fis = new FileInputStream("C:\" + filename);
        in = new ObjectInputStream(fis);
        time = (myTime)in.readObject();
        System.out.print(time);
        in.close();
        }
        catch(IOException ex)
        {
          ex.printStackTrace();
        }
        catch(ClassNotFoundException ex)
        {
          ex.printStackTrace();
        }
        // print out restored time
        System.out.println("Flattened time: " + time.callTime());
        System.out.println();
        // print out the current time
        System.out.println("Current time: " + Calendar.getInstance().getTime());
    }
 }

This what we are going to get
[email protected] time: Wed Feb 01 16:56:45 IST 2012
Current time: Wed Feb 01 17:25:00 IST 2012
I serialized time at 16:56:45 and I deserialized that time at 17:25:00

READ  Class SimpleDateFormat in Java

Interface Externalizable in java

The externalizable interface defines the methods that must be implemented by an object that wants complete control over the way it is serialized. The writeExternal() and readExternal() methods should be implemented to write and read object data in some arbitrary format, using the methods of the DataOutput and DataInput objects.

The Externalizable interface is an extension of the Serializable interface. Whereas a Serializable object is automatically saved and loaded (in most cases), an Externalizable object has sole responsibility for saving and loading its state via the writeExternal() and readExternal() methods. If a class implements the Externalizable interface, it must handle any versioning issues that occur.

The methods of Externalizable are public, which can pose a security risk. If security is a concern, Externalizable objects should not write or read sensitive information, or the Serializable interface should be used instead.

Externalizable objects must serialize their own fields, and are also responsible for serializing the fields of their superclasses. Most objects do not need to define a custom output format and can use the Serializable interface instead of Externalizable for serialization.

The structure of interface Externalizable is given as

public abstract interface java.io.Externalizable extends java.io.Serializable {
// Methods
public abstract void readExternal(ObjectInput in);
public abstract void writeExternal(ObjectOutput out);
}

The details of the class structure are given as follows:

public abstract void readExternal(ObjectInput in);

public abstract void readExternal(ObjectInput in) method reads an object from the given stream. This method has full responsibility for restoring the object’s state. The implementation of readExternal() should read data in the format that is written out by writeExternal().

In general, an implementation should call methods of DataInput to read primitive types and methods of ObjectInput to read objects, strings, and arrays.
Parameter
in -The object input stream to use.

public abstract void writeExternal(ObjectOutput out);

public abstract void writeExternal(ObjectOutput out) method writes an object to the given stream. This method has full responsibility for saving the object’s state. The implementation of writeExternal() should write data in the format that is read by readExternal().

In general, an implementation should call methods of DataOutput to write primitive types and methods of ObjectOutput to write objects, strings, and arrays.
Parameter
out -The object output stream to use.

Share and Enjoy !

1 thought on “Learn Object Serialization in Java in Quick and Easy Manner in 25 Minutes”

  1. I have been exploring for a little bit for any high quality articles or blog posts in this kind of area .

    Exploring in Yahoo I finally stumbled upon this site.
    Reading this information So i am glad to convey that I
    have an incredibly good uncanny feeling I found out just what I needed.
    I so much without a doubt will make sure to do not omit this site and provides it
    a glance regularly.

Leave a Comment

Your email address will not be published. Required fields are marked *