🔍 1)What is a HashMap
?
A HashMap
is a part of the Java Collection Framework that stores data in key-value pairs using a hash table.
📦 Package:
java.util.HashMap
🔑 Keys must be unique
❗ Allows onenull
key and multiplenull
values
🧠 How Does It Work?
-
Internally uses an array of buckets (array of
Node<K,V>
). -
Each key’s
hashCode()
is used to find a bucket index. -
If two keys have the same hash, a linked list or balanced tree (Java 8+) is used in that bucket (called collision handling).
📌 Key Characteristics
Feature | Description |
---|---|
Thread-safe | ❌ Not thread-safe |
Allows null key | ✅ Only one null key |
Allows null values | ✅ Any number of null values |
Order maintained | ❌ No (use LinkedHashMap if needed) |
Performance | ⚡ Fast O(1) for get/put in average case |
Load Factor (default) | 0.75 (when to resize) |
Initial Capacity (default) | 16 |
✅ Example – Basic Usage
🔧 Common Methods
Method | Description |
---|---|
put(K, V) | Add/update a key-value pair |
get(K) | Get value by key |
remove(K) | Remove key |
containsKey(K) | Check if key exists |
containsValue(V) | Check if value exists |
keySet() | Returns set of keys |
values() | Returns collection of values |
entrySet() | Returns set of key-value pairs |
🔁 Iteration Examples
🔹 Keys
🔹 Values
🔹 Entry (key-value pair)
🚫 Not Thread-Safe
In multi-threaded environments, use:
-
Collections.synchronizedMap(new HashMap<>())
-
OR prefer
ConcurrentHashMap
for better concurrency
⚙️ Internal Working (Simplified)
🆚 HashMap vs Other Maps
Feature | HashMap | LinkedHashMap | TreeMap | Hashtable |
---|---|---|---|---|
Ordering | ❌ | ✅ Insertion | ✅ Sorted keys | ❌ |
Null Keys | ✅ 1 | ✅ 1 | ❌ (throws NPE) | ❌ (throws NPE) |
Thread-safe | ❌ | ❌ | ❌ | ✅ (but obsolete) |
Performance | ✅ Fast | ✅ Slightly slower | ⚠️ Slower | ⚠️ Slower |
HashMap
Use HashMap
when:
-
You need fast key-value lookups
-
You don’t need order
-
You’re working in a single-threaded environment
-
You’re okay with allowing null key/value
❗ Avoid When
-
You need sorted data → use
TreeMap
-
You need insertion order → use
LinkedHashMap
-
You need thread safety → use
ConcurrentHashMap
orCollections.synchronizedMap()
🔍 2)What is a Synchronized Map?
A SynchronizedMap
is a wrapper around a regular map (like HashMap
) that makes all its method calls thread-safe using synchronization (i.e., internal synchronized
blocks).
🔒 It is useful when you want a thread-safe version of
HashMap
but don’t need the performance ofConcurrentHashMap
.
📦 How to Create a SynchronizedMap
Use Collections.synchronizedMap()
:
🧠 How It Works Internally
Collections.synchronizedMap()
returns a wrapper object where every method is synchronized on the map’s monitor (synchronized (map)
):
This ensures only one thread can access any method at a time — even for read operations.
⚠️ Iteration Must Be Manually Synchronized
❗ Failing to synchronize during iteration may cause
ConcurrentModificationException
.
✅ When to Use SynchronizedMap
Use SynchronizedMap
when:
-
You have low concurrency.
-
You want backward compatibility with old
HashMap
code. -
You want nulls to be allowed, unlike
ConcurrentHashMap
.
🔍 3)What is ConcurrentHashMap
?
ConcurrentHashMap
is a thread-safe, high-performance implementation of a hash map in Java, designed for concurrent access without the need for external synchronization.
📦 Package:
java.util.concurrent.ConcurrentHashMap
✅ Introduced in Java 5
✅ Why Use It?
-
We need safe access by multiple threads to a shared map.
-
We want better performance than synchronizing an entire
HashMap
or usingHashtable
. -
And it provides atomic methods like
putIfAbsent()
,compute()
,merge() so, we better to use
ConcurrentHashMap
🚫 Why not use HashMap in multi-threading
?
HashMap
is not thread-safe. Using it in multi-threaded code can lead to:
-
ConcurrentModificationException
-
Corrupted data
-
Infinite loops (e.g., during rehashing)
⚙️ How ConcurrentHashMap
Works
Java Version | Internal Design |
---|---|
Java 7 | Segment-based locking |
Java 8+ | Bucket-level fine-grained locks (no segments), uses CAS (Compare-And-Swap) |
🧑💻 Example – Basic Usage
❌ Null Values Are Not Allowed
Reason: null
is ambiguous in concurrent environments (e.g., get returning null — is it absent or null?).
🔄 Atomic Methods
Method | Purpose |
---|---|
putIfAbsent(key, val) | Insert only if key is missing |
compute(key, remapFn) | Update value atomically with a remapping function |
computeIfAbsent() | Lazily compute if key is missing |
computeIfPresent() | Update only if key is present |
merge() | Merge existing and new values |
forEach() | Safe concurrent iteration |
🔧 Multithreaded Example
🔐 ConcurrentHashMap vs SynchronizedMap vs Hashtable
Feature | HashMap |
Hashtable |
SynchronizedMap |
ConcurrentHashMap |
---|---|---|---|---|
Thread-safe | ❌ No | ✅ Yes | ✅ Yes (via wrapper) | ✅ Yes (better concurrency) |
Performance (multi-thread) | 🚫 Bad | ⚠️ Slow | ⚠️ Slower | ✅ Fast, scalable |
Null keys/values | ✅ Allowed | ❌ Disallowed | ✅ Allowed | ❌ Not allowed |
Read/Write Locking | ❌ None | Full sync (method) | Full sync (method) | Fine-grained (bucket-level) |
Use in modern apps | ❌ No | ❌ Obsolete | ⚠️ Legacy-compatible | ✅ Preferred |
✅ Summary
-
Use
ConcurrentHashMap
when you need a thread-safe map with high concurrency. -
Nulls are not allowed.
-
Provides atomic operations like
putIfAbsent()
,compute()
, andmerge()
. -
Faster and more scalable than legacy alternatives like
Hashtable
.
No comments:
Post a Comment