0% found this document useful (0 votes)
120 views

HashMap vs. ConcurrentHashMap vs. SynchronizedMap - How A HashMap Can Be Synchronized in Java - Crunchify

The document compares HashMap, ConcurrentHashMap, and SynchronizedMap in Java. HashMap is not thread-safe while ConcurrentHashMap and SynchronizedMap provide thread-safety. ConcurrentHashMap uses fine-grained locking at the bucket level for high concurrency, while SynchronizedMap uses coarse-grained locking of the entire map. The document includes code to test performance of the three maps by adding and retrieving 500k entries from each using multiple threads. ConcurrentHashMap has the best performance due to its fine-grained locking approach.

Uploaded by

Ashish Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

HashMap vs. ConcurrentHashMap vs. SynchronizedMap - How A HashMap Can Be Synchronized in Java - Crunchify

The document compares HashMap, ConcurrentHashMap, and SynchronizedMap in Java. HashMap is not thread-safe while ConcurrentHashMap and SynchronizedMap provide thread-safety. ConcurrentHashMap uses fine-grained locking at the bucket level for high concurrency, while SynchronizedMap uses coarse-grained locking of the entire map. The document includes code to test performance of the three maps by adding and retrieving 500k entries from each using multiple threads. ConcurrentHashMap has the best performance due to its fine-grained locking approach.

Uploaded by

Ashish Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

17/08/2020 HashMap Vs. ConcurrentHashMap Vs.

SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

About Java  Spring MVC  WordPress  Genesis WP Deals Advertise Contact

ADVERTISEMENT

Blog    Java and J2EE Tutorials    HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap – How a HashMa ...

HashMap Vs. ConcurrentHashMap Vs.


SynchronizedMap – How a HashMap can
be Synchronized in Java
Last Updated on August 3rd, 2018 by   App Shah    35 comments

 HashMap is a very powerful data structure in Java. We use it everyday and almost in all 
applications. There are quite a few examples which I have written before on How to
Implement Threadsafe cache, How to convert Hashmap to Arraylist?

We used Hashmap in both above examples but those are pretty simple use cases of
Hashmap. HashMap is a non-synchronized collection class.

Do you have any of below questions?

What’s the difference between ConcurrentHashMap and


Collections.synchronizedMap(Map)?
What’s the difference between ConcurrentHashMap and
Collections.synchronizedMap(Map) in term of performance?
ConcurrentHashMap vs Collections.synchronizedMap() 

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 1/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

Popular HashMap and ConcurrentHashMap interview questions

In this tutorial we will go over all above queries and reason  why and how we could
Synchronize Hashmap?

Why?
The Map object is an associative containers that store elements, formed by a combination
of a uniquely identify key  and a mapped value . If you have very highly concurrent

application in which you may want to modify or read key value in different threads then it’s
ideal to use Concurrent Hashmap. Best example is Producer Consumer which handles
concurrent read/write.

So what does the thread-safe Map means? If multiple threads access a hash map

concurrently, and at least one of the threads modifies the map structurally, it must be
synchronized externally to avoid an inconsistent view of the contents.

How?
There are two ways we could synchronized HashMap

. Java Collections synchronizedMap() method

. Use ConcurrentHashMap

//Hashtable
Map<String, String> normalMap = new Hashtable<String, String>();

//synchronizedMap
synchronizedHashMap = Collections.synchronizedMap(new HashMap<String, String>());

//ConcurrentHashMap
concurrentHashMap = new ConcurrentHashMap<String, String>();

ConcurrentHashMap
You should use ConcurrentHashMap when you need very high concurrency in your
 
project.
It is thread safe without synchronizing the whole map .

Reads can happen very fast while write is done with a lock.
There is no locking at the object level.
The locking is at a much finer granularity at a hashmap bucket level.
ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one
thread tries to modify it while another is iterating over it.
ConcurrentHashMap uses multitude of locks.

SynchronizedHashMap
Synchronization at Object level.
Every read/write operation needs to acquire lock. 

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 2/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

Locking the entire collection is a performance overhead.


This essentially gives access to only one thread to the entire map & blocks all the
other threads.
It may cause contention.
SynchronizedHashMap returns Iterator , which fails-fast on concurrent modification.

Now let’s take a look at code

. Create class  CrunchifyConcurrentHashMapVsSynchronizedHashMap.java

. Create object for each HashTable, SynchronizedMap


and CrunchifyConcurrentHashMap

. Add and retrieve 500k entries from Map

. Measure start and end time and display time in milliseconds

. We will use ExecutorService to run 5 threads in parallel

Here is a Java code:

package crunchify.com.tutorials;

import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* @author Crunchify.com
*
*/

public class CrunchifyConcurrentHashMapVsSynchronizedMap {

public final static int THREAD_POOL_SIZE = 5;

public static Map<String, Integer> crunchifyHashTableObject = null;


public static Map<String, Integer> crunchifySynchronizedMapObject = null;
public static Map<String, Integer> crunchifyConcurrentHashMapObject = null;
 
public static void main(String[] args) throws InterruptedException {

// Test with Hashtable Object


crunchifyHashTableObject = new Hashtable<String, Integer>();
crunchifyPerformTest(crunchifyHashTableObject);

// Test with synchronizedMap Object


crunchifySynchronizedMapObject = Collections.synchronizedMap(new HashMap<Stri
crunchifyPerformTest(crunchifySynchronizedMapObject);

// Test with ConcurrentHashMap Object


crunchifyConcurrentHashMapObject = new ConcurrentHashMap<String, Integer>();
crunchifyPerformTest(crunchifyConcurrentHashMapObject);

public static void crunchifyPerformTest(final Map<String, Integer> crunchifyThrea


https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 3/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify
System.out.println("Test started for: " + crunchifyThreads.getClass());
long averageTime = 0;
for (int i = 0; i < 5; i++) {

long startTime = System.nanoTime();


ExecutorService crunchifyExServer = Executors.newFixedThreadPool(THREAD_P

for (int j = 0; j < THREAD_POOL_SIZE; j++) {


crunchifyExServer.execute(new Runnable() {
@SuppressWarnings("unused")
@Override
public void run() {

for (int i = 0; i < 500000; i++) {


Integer crunchifyRandomNumber = (int) Math.ceil(Math.rand

// Retrieve value. We are not using it anywhere


Integer crunchifyValue = crunchifyThreads.get(String.valu

// Put value
crunchifyThreads.put(String.valueOf(crunchifyRandomNumber
}
}
});
}

// Initiates an orderly shutdown in which previously submitted tasks are


// has no additional effect if already shut down.
// This method does not wait for previously submitted tasks to complete e
crunchifyExServer.shutdown();

// Blocks until all tasks have completed execution after a shutdown reque
// interrupted, whichever happens first.
crunchifyExServer.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

long entTime = System.nanoTime();


long totalTime = (entTime - startTime) / 1000000L;
averageTime += totalTime;
System.out.println("500K entried added/retrieved in " + totalTime + " ms"
}
System.out.println("For " + crunchifyThreads.getClass() + " the average time
}
}

shutdown() means the executor service takes no more incoming tasks.

awaitTermination() is invoked after a shutdown request.


 

And hence, you need to first shutdown the serviceExecutor and then block and wait for
threads to finish.

Eclipse Console Result:

Test started for: class java.util.Hashtable


500K entried added/retrieved in 1832 ms
500K entried added/retrieved in 1723 ms
500K entried added/retrieved in 1782 ms
500K entried added/retrieved in 1607 ms
500K entried added/retrieved in 1851 ms
For class java.util.Hashtable the average time is 1759 ms

Test started for: class java.util.Collections$SynchronizedMap


500K entried added/retrieved in 1923 ms 

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 4/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify
500K entried added/retrieved in 2032 ms
500K entried added/retrieved in 1621 ms
500K entried added/retrieved in 1833 ms
500K entried added/retrieved in 2048 ms
For class java.util.Collections$SynchronizedMap the average time is 1891 ms

Test started for: class java.util.concurrent.ConcurrentHashMap


500K entried added/retrieved in 1068 ms
500K entried added/retrieved in 1029 ms
500K entried added/retrieved in 1165 ms
500K entried added/retrieved in 840 ms
500K entried added/retrieved in 1017 ms
For class java.util.concurrent.ConcurrentHashMap the average time is 1023 ms

Join the Discussion

Share & leave us some comments on what you think about this topic or if you like to add

something.

Share:      

Other Popular Articles...


. What is Java Synchronized Collections? Complete Tutorials using java.util.Collections

. Java Hashmap – containsKey(Object key) and containsValue(Object value) – Check if

Key/Value Exists in Map

. Implement Simple Threadsafe Cache using HashMap without using Synchronized

Collection

. How to use net.jodah.ExpiringMap Maven Java Utility to Remove Expired Objects from

HashMap Automatically – Complete Java Tutorial

. How to convert HashMap to ArrayList in Java?

. Java: How to Get Random Key-Value Element From HashMap

 Java and J2EE Tutorials  Hashmap


 

I WANT TO...

Optimize WordPress Plugins we use Get FREE Domain & Hosting Learn SEO

About App Shah


I'm an Engineer by profession, Blogger by passion & Founder of Crunchify, LLC,

the largest free blogging & technical resource site for beginners. Love SEO,

SaaS, #webperf, WordPress, Java. With over 16 millions+ pageviews/month, Crunchify has 

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 5/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

changed the life of over thousands of individual around the globe teaching Java & Web Tech for

FREE. Get latest update on  and .

Subscribe To Newsletter…
Get Early Access To New Articles, Plugins, Discount Codes And Brief Updates About What's
New With Crunchify! Join Over 16 Million Monthly Readers... 

E-Mail Address SUBSCRIBE!

Over 16 million readers


Get fresh content from Crunchify

      

 SEARCH

TOP TECH TUTORIALS

 NEW In Java8 Join List Of Object &


Build RESTful Service Using JAX-RS
& Jersey

 Simplest Spring MVC Hello World


& Spring Boot Tutorial

 Top 10 Java Interview Questions


Answers & JavaScript & Validate
Username, Phone Field

 Better Logging Tips & Create Your


Own Logging Level Using Log4j

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 6/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

 Sort A HashMap By Key & Value &


Read And Parse CSV Tutorial

 NEW Implement A LinkedList Class


From Scratch & Enable Pretty Print
In JSON Processing API

BASIC JAVA TECH

Singleton Pattern Java Caching

LinkedList Iterator Java Abstract

Java Static Intro Java Interface

Github OAuth Sorting Algorithm

Semaphore & Mutex

Java Reflection

Java NIO (Non-blocking)

SOAP vs REST .zip file by Maven

Modern, Secure & Fast Managed


WordPress Hosting. Check it out.

USEFUL WORDPRESS GUIDE

 NEW Start 1st WordPress Blog & 15


Essential Optimization Tips

 Leverage .Htaccess To Speed Up


WordPress & Stop Loading
Unnecessary Files On Site

 Top 5 Basic SEO Tips &


Importance Of Keyword Research

  Better Cleanup WordPress Header


Section & Fix CPanel CPU Issue

 Google Form As Ultimate


WordPress Contact Form & Load
WordPress Fonts Locally (Speed
Tips)

 16 Proven Ways To Get Quality


Backlinks & Better Upgrade To PHP
7.1

 NEW Secure WordPress Login


Area & Cloak Affiliate Links
Without WordPress Plugin

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 7/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

WORDPRESS TUNING TIPS

Install WP Locally WordPress CPT

Disable Cron Jobs Modify 404 Page

Scroll To Top GenesisWP Hooks

Add Bitly Shortlink

Adsense without Plugin

Plugins we Use Top Backup Plugins

Domain Authority Tips

Interlinking Tips Setup Forum

Top Blogging Top Tech Recently Crunched…


Categories… Categories…
How to create simplest Spring Boot Rest Service
 
SEO 101 Tutorials Java & J2EE listening on port 8081?

WordPress Optimization and Tutorials Eclipse IDE Tutorials How to create 1st Spring Boot HelloWorld Application

Genesis WP Android Dev Tutorials in IntelliJ IDEA with few simple steps?

Blogging Apache Tomcat Tutorials How to use Spring Framework StopWatch() to Log

ExecutionTime and ElapseTime of any Java Thread


Making Money Online Design & Dev
How to Reverse a String in Java? Total 7 different
functions.php Hacks Interview Questions Answers
ways…
WebHosting JavaScript
In Java How to Sort a Map on the Values? The Map
style.css Hacks Spring MVC and Spring Boot
Interface – Java Collections
WooCommerce Tutorials

Maven

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 8/9
17/08/2020 HashMap Vs. ConcurrentHashMap Vs. SynchronizedMap - How a HashMap can be Synchronized in Java • Crunchify

ADVERTISE SITEMAP SETUP FORUM PRO SERVICES COOKIE POLICY

      

   2020 Crunchify, LLC. Hosted at Kinsta  •  Built on Genesis Themes.
DCMA Disclaimer and Privacy Policy.
Noticed a bug? Report it here.

 

https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-hashmap-can-be-synchronized-in-java/ 9/9

You might also like