April 25, 2016

Serialization Interview Questions and Answers for Experienced Developers

What is Serialization in Java?
Serialization is a process by which you can save or transfer the state of an object by converting it to a byte stream.

During Serialization, the Object is converted into a binary format ,which can be persisted into disk or sent over network to any other running Java virtual machine. During deserialization the reverse process is performed by creating object from binary stream.

How to make a Java class Serializable?
This can be done in java by implementing java.io.Serializable interface, which is a marker interface and needs to be implemented for transferring an object over a network or persistence of its state to a file. Since its a marker interface, it does not contain any methods. Implementation of this interface enables the conversion of object into byte stream and thus can be transferred. The object conversion is done by the JVM using its default serialization mechanism.

Decision to making a Class Serializable should be taken concisely because though near term cost of making a Class Serializable is low, long term cost is substantial and it can potentially limit your ability to further modify and change its implementation. Like any public API, serialized form of an object becomes part of public API and when you change structure of your class by implementing addition interface, adding or removing any field can potentially break default serialization, this can be minimized by using a custom binary format but still requires lot of effort to ensure backward compatibility.

What is use of serialVersionUID?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type

Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value called as serialVersionUID or suid.

When the serialized object is retrieved, the JVM first evaluates the 'suid' of the serialized class and compares the 'suid' value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

The only way to get rid of the InvalidClassException is to recompile and deploy the application again.

What are the compatible changes and incompatible changes in Java Serialization Mechanism?
Compatible changes are:
  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree
Incompatible changes:
  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field
If we explicitly mention the suid using the statement, then if any of the mentioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.
private final static long serialVersionUID =  

ALSO READ: Serialization of Singleton class..

What is the Difference between Externalizable and Serializable Interfaces?
Serializable is a marker interface therefore you are not forced to implement any methods, however Externalizable contains two methods readExternal() and writeExternal() which must be implemented.

If Serializable  is used, Constructor is not called during deSerialization. While in case of Externalizabl, Constructor is called during deSerialization.

Serializable interface provides a inbuilt serialization mechanism to you which can be in-efficient at times. However Externalizable interface is designed to give you greater control over the serialization mechanism. The two methods provide you immense opportunity to enhance the performance of specific object serialization based on application needs.

Serializable interface provides a default serialization mechanism, on the other hand, Externalizable interface instead of relying on default Java Serialization provides flexibility to control this mechanism.

One can drastically improve the application performance by implementing the Externalizable interface correctly. However there is also a chance that you may not write the best implementation, so if you are not really sure about the best way to serialize stick to the default implementation using Serializable interface.

e.g  when you have a big Java object with hundreds of attributes and you want to serialize only a dozen dynamically selected attributes to keep the state of the object you should use Externalizable interface writeExternal method to selectively serialize the chosen attributes.

In case you have small objects and you know that most or all attributes are required to be serialized then you should be fine with using Serializable interface and use of transient variable as appropriate.

Serialization using Serializable Interface
OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects...");

DeSerialization using Serializable Interface
InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, displaying employee objects...");
Employee emp;

Serialization using Externalizable  Interface
public void writeExternal(ObjectOutput oo) throws IOException {

DeSerialization using Externalizable  Interface
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {

What if Serialization is not available, is any other alternative way to transfer object over network?
  • We can can convert JSON to transfer the object. JSON is helpful in stringifying and de stringifying object.
  • Hibernate (ORM tool) helps in persisting object as it in database and later we can read persisted object.
  • We can convert object into XML (as done in web services) and transfer object over network.

Is constructor of class called during DeSerialization process?
It depends on whether our object has implemented Serializable or Externalizable.
If Serializable has been implemented - constructor is not called during DeSerialization process.
But, if Externalizable has been implemented - constructor is called during DeSerialization process.

Is constructor of super class called during DeSerialization process of subclass?
It is depends on whether our superclass has implemented Serializable or not.
If superclass has implemented Serializable - constructor is not called during DeSerialization process.
If superclass has not implemented Serializable - constructor is called during DeSerialization process.

How can subclass avoid Serialization if its superClass has implemented Serialization interface?
If superClass has implemented Serializable that means subclass is also Serializable (as subclass always inherits all features from its parent class), for avoiding Serialization in sub-class we can define writeObject() method and throw NotSerializableException(). e.g :

private void writeObject(ObjectOutputStream os) throws NotSerializableException {
throw new NotSerializableException("This class cannot be Serialized");

What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime.

If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?
Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn't be possible to stop that, hence even if classes higher in hierarchy implements Serializable interface, there constructor will be executed.

Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If the super class implements Serializable interface, then the subclass will also be Serializable, since you can not unimplemented an interface its not really possible to make it Non Serializable class. To avoid serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method.

hich kind of variables is not serialized during Java Serialization?
The answer is static and transient. The static variables belong to the class are not the part of the state of the object so they are not saved as the part of serialized object. Also, Transient variables are also not included in java serialization process.

Why static variables are not serialized?
Saving static variables with each serialized object would have following problems
It will make redundant copy of same variable in multiple objects which makes it in-efficient.
The static variable can be modified by any object and a serialized copy would be stale or not in sync with current value.

What will be the value of transient variable after de-serialization?
It’s default value. e.g. if the transient variableis an int, it’s value after deserialization will be zero.

How to Serialize a collection in java? What will happen if we have used List, Set and Map as member of class that need to be serialized?
All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. All the commonly used collection classes like java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not really need to write anything specific to serialize collection objects. However you should keep following things in mind before you serialize a collection object - Make sure all the objects added in collection are Serializable. - Serializing the collection can be costly therefore make sure you serialize only required data isntead of serializing the whole collection. - In case you are using a custom implementation of Collection interface then you may need to implement serialization for it.

-K Himaanshu Shuklaa

No comments:

Post a Comment

RSSChomp Blog Directory