BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to synchronize HashMap in Java with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: 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 this tutorial we will see how to synchronize HashMap.

Example:

In this example we have a HashMap<Integer, String> it is having integer keys and String type values. In order to synchronize it we are using Collections.synchronizedMap(hashmap)  it returns a thread-safe map backed up by the specified HashMap.

Important point to note in the below example:
Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly (As we did in the below code).

Syntax:

Map map = Collections.synchronizedMap(new HashMap());
...
//This doesn't need to be in synchronized block
Set set = map.keySet();
// Synchronizing on map, not on set
synchronized (map) {  
      // Iterator must be in synchronized block
      Iterator iterator = set.iterator(); 
      while (iterator.hasNext()){
          ...
      }
}

Complete Code:

package beginnersbook.com;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
public class HashMapSyncExample {
    public static void main(String args[]) {
         HashMap<Integer, String> hmap= new HashMap<Integer, String>();
         hmap.put(2, "Anil");
         hmap.put(44, "Ajit");
         hmap.put(1, "Brad");
         hmap.put(4, "Sachin");
         hmap.put(88, "XYZ");

         Map map= Collections.synchronizedMap(hmap);
         Set set = map.entrySet();
         synchronized(map){
             Iterator i = set.iterator();
             // Display elements
             while(i.hasNext()) {
                Map.Entry me = (Map.Entry)i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
             }
         }
    }
}

Output:

1: Brad
2: Anil
4: Sachin
88: XYZ
44: Ajit

Top Related Articles:

  1. How to loop LinkedList in Java
  2. OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
  3. LinkedHashSet Class in Java with Example
  4. How to sort Hashtable in java
  5. Constructor Overloading in Java with examples

Tags: Collections, Java-HashMap

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. munni says

    July 2, 2014 at 1:07 PM

    What’s the use of synchronizing hashmap?
    As sync says only one at a time — which part of example says that only one is getting accessed?
    Basically i wanted to know the difference b/w sync and non sync hashmap using multi threaded example and basically showing the difference

    It would be great it u cud clarify my questions.

    Reply
  2. Chinmayee Das says

    April 3, 2015 at 11:38 AM

    Hello,

    In the above program, how the output came, i am not getting, in which way, its printing the result?? can u please brief about this..

    Thanks
    chinmayee

    Reply
    • Rajeev Shrikar says

      June 10, 2016 at 8:14 AM

      what error you are getting? It executed perfectly for me.
      May be you have kept package name as it is, try removing that line or keep the java file according to the package name.

      Reply
  3. Rajeev Shrikar says

    June 10, 2016 at 8:09 AM

    simple and easily understandable.
    Please show a program in multi threaded environment too!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap