Commit ae6e2b7
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- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+1
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
| |||
29 | 27 | | |
30 | 28 | | |
31 | 29 | | |
32 | | - | |
33 | 30 | | |
34 | 31 | | |
35 | | - | |
| 32 | + | |
0 commit comments