Monday, August 29, 2016

Serialization and Deserialization in Java


Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization.

Serialization is usually used when there is need to send your data over network or to store 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 Java object’s values/states to bytes to send it over network or to save it. On other hand, Deserialization is conversion of byte code to corresponding java objects.

A class must implement Serializable interface present in java.io package in order to serialize its object successfully. Serializable is a marker interface that adds serializable behaviour to the class implementing it.

Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects which include,
  • java.io.serializable
  • java.io.Externalizable
  • ObjectInputStream
  • and ObjectOutputStream etc.

Marker interface
Marker Interface is a special interface in Java without any field and method. Marker interface is used to inform compiler that the class implementing it has some special behaviour or meaning. Some example of Marker interface are,
  • java.io.Serializable
  • java.lang.Cloneable
  • java.rmi.Remote
  • java.util.RandomAccess
All these interfaces do not have any method and field. They only add special behavior to the classes implementing them. However, marker interfaces have been deprecated since Java 5, they were replaced by Annotations. Annotations are used in place of Marker Interface that play the exact same role as marker interfaces did before.

Concept of serialVersionUID :
serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.

Signature of writeObject() and readObject()
writeObject() method of ObjectOutputStream class serializes an object and send it to the output stream.
public final void writeObject(object x) throws IOException
readObject() method of ObjectInputStream class references object out of stream and deserialize it.
public final Object readObject() throws IOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state then declare it either static or transient based on your need and it will not be included during java serialization process.

Serializing an Object
import java.io.*;
class studentinfo implements Serializable
{
 String name;
 int rid;
 static String contact;
 studentinfo(string n, int r, string c)
 {
  this.name = n;
  this.rid = r;
  this.contact = c;
 }
}

class Test
{
 public static void main(String[] args)
 {
 try
 {
  Studentinfo si = new studentinfo("Abhi", 104, "110044");
  FileOutputStream fos = new FileOutputStream("student.ser");
  Objectoutputstream oos = new ObjectOutputStream(fos);
  oos.writeObject(si);
  oos.close();
  fos.close();
  }
  catch (Exception e)
  { e. printStackTrace(); }
 }
}
Object of Studentinfo class is serialized using writeObject() method and written to student.ser file.

Deserialization of Object
import java.io * ;
class DeserializationTest
{
 public static void main(String[] args)
 {
  studentinfo si=null ;
  try 
  {
   FileInputStream fis = new FileInputStream("student.ser");
   ObjectOutputStream ois = new ObjectOutputStream(fis);
   si = (studentinfo)ois.readObject();
  }
  catch (Exception e)
   { e.printStackTrace(); }
  System.out.println(si.name);
  System.out. println(si.rid);
  System.out.println(si.contact);
 }
}
Output :
Abhi
104
null
Contact field is null because, it was marked as static and as we have discussed earlier static fields does not get serialized.

NOTE: Static members are never serialized because they are connected to class not object of class.

transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized we can mention it transient. transient keyword will prevent that data member from being serialized.
class studentinfo implements Serializable
{
 String name;
 transient int rid;
 static String contact;
}
  • Making a data member transient will prevent its serialization.
  • In this example rid will not be serialized because it is transient, and contact will also remain unserialized because it is static.

What if superclass is Serializable?
If superclass is serialzable then all its subclasses are automatically serializable.

What if superclass is not Serializable?
If super class is not serializable then we have to handle it quite differently.
If superclass is not serializable then it must have no argument constructor.

If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. so here name is inherited from person so during deserialization,name is initialized to default.

What if superclass is Serializable but you don’t want subclass to be Serializable
If you don’t want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.



HashMap Interview Questions in java

Can we synchronize a HashMap?
Yes, a HashMap can be synchronized using its synchronizedMap() method.
Map s = Collections.synchronizedMap(new HashMap(…));
  
Can we add duplicate keys in a HashMap?
What happens to the value if we add a duplicate key with new value? Is is discarded or is it overwritten?

If a key already exists in a HashMap and we try to add another value for the same key, then the old value of the key will be replaced with the new value.

What is the difference between a HashMap and a Hashtable?
– HashMap is not synchronized whereas Hashtable is synchronized.
– HashMap allows a null key and null values. Hashtable does not allow null keys or values.
– Since HashMap isn’t synchronized, it is faster compared to a HashTable.

- Iterator in hashmap is fail-fast. But enum in Hashtable is not fail-fast. Fail-fast means if one thread is iterating over a map and another is trying to modify it by adding/deleting elements, it will throw ConcurrentModificationException

What is an IdentityHashMap? How is it different from a normal HashMap?
IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements.
Instead of using the equals() method to compare entries as in HashMap, IdentityHashMap compares them using the == operator
So, two object references are considered equal if they refer to the same object instance.

What is a WeakHashMap?
A WeakHashMap implements a map that uses “weak keys”.
This allows an element in the map to be garbage-collected when the key is unused.
  
What is the difference between remove() and clear() methods in HashMap ?
We can remove entries from HashMap using remove(key) or clear() methods.
remove(key) removes the mapping for the key specified in parameter.
clear() method removes all the entries from the HashMap and returns void.
  
Explain how HashMap works?
HashMap works on the principle of hashing.

put() and get() methods are used to store and retrieve data from hashmap.
It has a number of buckets which stores key-value pairs.

when put() is called, hashmap implementation calls hashcode() on the key to identify the bucket location… then stores both key+value in the bucket
when get() is called, the hashcode() on key is used to identify the bucket location and the value if returned.

If two key objects have same hashcode, bucket location will be the same and collision occurs in hashmap.
Inside the bucket, data is stored in linked list, so in collision scenario, it will get added to next node.
So, when get() is called, the hashcode() would point to the bucket location, then the use key.equals() to find the correct node in the linked list.
  
What is the difference between ConcurrentHashMap and Hashtable?
 Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

Since ConcurrentHashMap introduced concept of segmentation , no matter how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.

What is the difference between ConcurrentHashMap and Collections.synchronizedMap ?
ConcurrentHashMap is designed for concurrency and improve performance while HashMap which is non synchronized by nature can be synchronized by applying a wrapper using Collections.synchronizedMap.




Java Design Pattern Interview questions

If two different class loaders load a singleton class, would they load it twice ?
Two objects loaded by different class loaders are never equal even if they carry the same values.
So, each class loader will have its own singleton.

What is Decorator design pattern?
The decorator design pattern attaches responsibilities to objects at runtime.
BufferedInputStream in java.io is an example of Decorator. It wraps around a InputStream and provide additional buffering functionality.

What is Strategy design pattern?
Strategy design pattern lets you swap new algorithms and processes into your program without
affecting the objects that use them.
AWT containers delegate the layout to layout managers. Layout managers use strategy pattern to for appropriate layout.

What is Iterator Design pattern?
 Iterator pattern is used to iterate over a collection sequentially and provide a way the access the individual elements.

What is Factory pattern?
 Factory pattern abstracts the object creation process from the code that uses the objects.

What is Front Controller design pattern?
Front controller suggest using a single servlet for centralizing request handling and delegating functions like validation and business process handling to helpers.

What is Composite view pattern?
A composite view is made of several sub-views.
A JSP page can use a header jsp, footer jsp etc.

What is View Helper pattern?
In this pattern, the view delegates processing responsibilities to helper classes.
Implemented using Javabeans.

Difference between Service to Worker pattern and Dispatcher View pattern.
Both pattern use Front controller combined with Helpers with Dispatcher component.
In Service to worker, front controller delegates content retrieval to View Helpers. Controller also takes care of tasks like authentication, authorization etc.
In Dispatcher View, Controller does not delegate content retrieval to helpers. Most of the work is done by views.