Commit 6c67bd3
committed
feat(ThreadSafeHashTable): demonstrate synchronized thread-safe operations in Hashtable
What
- Added `ThreadSafeHashTable` class to showcase how `Hashtable` ensures thread safety with multiple writers.
- Spawned two threads:
- Thread1 inserts keys 0 → 1000 with value `"New Thread1 Running"`.
- Thread2 inserts keys 1000 → 1999 with value `"Thread2"`.
- Waited for both threads (`join()`).
- Printed final size of the map (`2000` entries).
Why
- To illustrate that unlike `HashMap`, all methods of `Hashtable` are synchronized.
- Validates safe concurrent access without external synchronization.
- Highlights the trade-off: thread safety but slower performance compared to non-synchronized collections.
How
- Step 1: Create a `Hashtable<Integer,String>` instance.
- Step 2: Define first thread to `put` entries for keys 0–1000.
- Step 3: Define second thread to `put` entries for keys 1000–1999.
- Step 4: Start both threads and `join()` to ensure completion.
- Step 5: Print `map.size()`, expected `2000`.
Logic
- Inputs: hard-coded key ranges (0–1999).
- Outputs: `"Final size of HashTable: 2000"`.
- Flow:
1. Instantiate `Hashtable`.
2. Launch two concurrent writers.
3. Synchronization in `Hashtable` ensures correctness.
4. Join threads.
5. Print map size.
Real-life applications
- Legacy multi-threaded applications before `ConcurrentHashMap`.
- Small-scale shared maps where built-in synchronization is sufficient.
- Teaching concurrency safety basics in Java collections.
Notes
- `Hashtable` synchronizes all operations (method-level).
- This avoids corruption but limits scalability under high contention.
- For modern concurrent workloads, prefer `ConcurrentHashMap`.
- Demonstrates the classic synchronized map pattern and its impact.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent dfb58bd commit 6c67bd3
File tree
1 file changed
+56
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Hash Table/src
1 file changed
+56
-0
lines changedLines changed: 56 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
0 commit comments