• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Synchronized Map and ConcurrentHashMap

May 4, 2015 By j2eereference Leave a Comment

Synchronized Map and ConcurrentHashMap

In this article lets see the difference between Hashtable , Synchronized Map and ConcurrentHashMap,

Hashtable :

Hashtable is a legacy class from JDK 1.1, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized .Hence the operation on Hashtable makes them quite slow if number of thread are more.

Synchronized Map:

Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. Only difference between Hashtable and SynchronizedMap is that SynchronizedMap is not a legacy and you can wrap any Map to create it’s synchronized version by using Collections.synchronizedMap() method.

ConcurrentHashMap:

The ConcurrentHashMap class provides a concurrent version of the standard HashMap. This is an improvement on the synchronizedMap functionality provided in the Collections class.

Unlike Hashtable and Synchronized Map, it never locks whole Map, instead it divides the map in segments and locking is done on those. It perform better if number of reader threads are greater than number of writer threads.

ConcurrentHashMap by default is separated into 16 regions and locks are applied. This default number can be set while initializing a ConcurrentHashMap instance. When setting data in a particular segment, the lock for that segment is obtained. This means that two updates can still simultaneously execute safely if they each affect separate buckets, thus minimizing lock contention and so maximizing performance.

ConcurrentHashMap doesn’t throw a ConcurrentModificationException 

ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it. Lets see this with the below example code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
 
public class CHM {
public static void main(String[] args) {
//concurrentHashMap
ConcurrentHashMap<String, String> chm = new ConcurrentHashMap<String, String>();
chm.put("1","One");
chm.put("2","Two");
Iterator itchm = chm.keySet().iterator();
while(itchm.hasNext()){
String key = itchm.next();
if(key.equals("1")) chm.put(key+"newObj", "newObject");
}
System.out.println("After Iterating Hashmap");
//Hashmap
HashMap&lt;String, String&gt; hashMap = new HashMap&lt;String, String&gt;();
hashMap.put("1","One");
hashMap.put("2","Two");
Iterator it = hashMap.keySet().iterator();
while(it.hasNext()){
String key = it.next();
if(key.equals("1")) hashMap.put(key+"newObj", "newObject");
}
System.out.println("After Iterating consurrentHashmap");
}
}

Output:

After Iterating Hashmap
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at j2eereference.CHM.main(CHM.java:26)

Here  we can notice that ConcurrentHashMap takes care of any new entry in the map whereas HashMap throws ConcurrentModificationException.

any update in the structure or the number of entry in the collection object will trigger this exception thrown by iterator. HashMap implementation contains a variable to count the number of modifications and iterator use it when we call its next() method to get the next entry.This is not available in ConcurrentHashMap implementation.

Difference between synchornizedMap and ConcurrentHashMap

Collections.synchornizedMap(HashMap)  will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object while in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon concurrency level and only locking particular portion instead of locking whole Map.

ConcurrentHashMap does not allow null keys or null values while synchronized HashMap allows one null keys.

Related Posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.