Serialize vs Synchronized HashMap

In the tutorial, we will discuss Serialize vs synchronized HashMap in Java with an example.

 

Serialized HashMap in Java

HashMap class is serialized by default which means we need not implement Serializable interface in order to make it eligible for Serialization. Let’s discuss the serialization and De-serialization first.

 

Serialization  – Serialization is a process of writing an Object into the file along with its attributes and content. Object Serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

 

De-Serialization – De-Serialization is a process of reading the Object and it’s properties from a file along with the Object’s content.

 

Let’s understand the HashMap Serialization with an example. In the below example we are storing the HashMap content in a Serialize.ser serialized file.

Output:

Serialized HashMap data is saved in Serialize.ser

 

In the above example, we have seen the implementation of HashMap Serialization.

 

De-Serialization – Now we will see, How can we reproduce the HashMap object and it’s content from a serialized file which we have created in the last example.

Output:

Deserialized HashMap is : 
key: 1 & Value: SeleniumBix
key: 2 & Value: Chauhan
key: 4 & Value: Mirilla
key: 5 & Value: Anshul
key: 10 & Value: Kinghtly

 

Synchronized HashMap in Java

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly. In order to synchronize it we are using Collections.synchronizedMap(hashmap) . It returns a thread-safe map backed up by the specified HashMap.

Let’s understand this with an easy example.

Output:

key: 1 & Value: SeleniumBix
key: 2 & Value: Chauhan
key: 4 & Value: Mirilla
key: 5 & Value: Anshul
key: 10 & Value: Kinghtly

 

We have seen the example of serialized vs synchronized HashMap.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

1 Comment
  1. Mark Sim 4:36 PM / August 26, 2016 - Reply

    Hey .. Nice writ, Please some tutorial on Java Regex …. Thanks once again

Leave a Reply