Object Serialization in Java

0
137
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

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??

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.

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.

The interface Structure of the Serializable is given as

public interface 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:-
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.

Disadvantages:-

  • 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.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here