- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to make a class thread-safe in Java?
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads.
The 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.
Example:
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 hmap = new HashMap(); hmap.put(2, "Raja"); hmap.put(44, "Archana"); hmap.put(1, "Krishna"); hmap.put(4, "Vineet"); 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()); } } } }
In the above example, we have a HashMap 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.
Output:
1: Krishna 2: Raja 4: Vineet 88: XYZ 44: Archana
- Related Articles
- How to make a collection thread safe in java?
- Make your collections thread-safe in C#
- How to understand StringBuffer is thread-safe and StringBuilder is non-thread-safe in Java?\n
- Is Java matcher thread safe in Java?
- Is Swing thread-safe in Java?
- Which collection classes are thread-safe in Java?
- How to create a thread by using anonymous class in Java?
- Thread-Safe collections in C#
- How to use isAlive() method of Thread class in Java?
- How to make a class singleton in Java?\n
- Thread Safe Concurrent Collection in C#
- What is the Thread class in Java?
- Make a class final in Java
- How to create a thread in Java
- Do you think a Python dictionary is thread safe?

Advertisements