Skip to content

Commit ae6e2b7

Browse files
committed
feat(ThreadSafetyInHashMap): add demo showing non-thread-safe behavior of HashMap
What - Added ThreadSafetyInHashMap class. - Created a shared HashMap<Integer,String>. - Spawned two threads: • thread1 inserts keys 0–999 with value "Thread1". • thread2 inserts keys 1000–1999 with value "Thread2". - Joined both threads to ensure completion. - Printed final size of the HashMap. Why - To demonstrate that HashMap is not thread-safe under concurrent modifications. - Highlights that concurrent put() calls can cause: • Lost updates • Unexpected final sizes • Possible data corruption in extreme cases - Sets the stage for introducing thread-safe alternatives like ConcurrentHashMap. How - Shared mutable HashMap passed implicitly to both threads. - Each thread performs 1000 put operations. - After both complete, program prints map.size(). - Expected size = 2000, but due to race conditions may differ on some runs. Logic - Inputs: - Keys 0–1999 spread across two threads. - Values "Thread1" and "Thread2". - Outputs: - Final map size (should be 2000 in sequential scenario). - Actual size may be < 2000 under race conditions. - Flow: 1. Initialize HashMap. 2. Start two writer threads. 3. Wait for completion using join(). 4. Print map size. - Constraints: - No synchronization used (deliberate). - Demonstrates unsafe concurrent access. - Complexity: - Each thread: O(n) inserts (n=1000). - Overall O(2000) operations. Real-life applications - Serves as cautionary example for multi-threaded programs using HashMap. - Encourages using: • Collections.synchronizedMap(new HashMap<>()) • ConcurrentHashMap • Or explicit synchronization - Useful in teaching thread-safety fundamentals in Java collections. Notes - HashMap is designed for single-threaded use. - Concurrent modifications without synchronization can lead to data loss. - Thread-safe alternatives should be preferred in concurrent environments. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent ef98ff4 commit ae6e2b7

File tree

1 file changed

+1
-4
lines changed

1 file changed

+1
-4
lines changed

Section25CollectionFramework/src/HashMapDemo/ThreadSafetyInHashMap.java renamed to Section 25 Collections Frameworks/Map Interface/HashMap/src/ThreadSafetyInHashMap.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
package HashMapDemo;
2-
31
import java.util.HashMap;
42

53
public class ThreadSafetyInHashMap {
@@ -29,7 +27,6 @@ public static void main(String[] args) {
2927
} catch (InterruptedException e) {
3028
e.printStackTrace();
3129
}
32-
3330
System.out.println("Final size of HashMap: " + map.size());
3431
}
35-
}
32+
}

0 commit comments

Comments
 (0)