Skip to content

Commit 36315f3

Browse files
Create ConcurrentHashMapDemo.java
1 parent 90e1f74 commit 36315f3

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package learnCollections;
2+
3+
import java.util.concurrent.ConcurrentHashMap;
4+
5+
/*
6+
ConcurrentHashMap
7+
|
8+
---------------------------------------------------------
9+
| | | | | | |
10+
Segment0 Segment1 Segment2 Segment3 Segment4 Segment5 Segment6
11+
| | | | | | |
12+
HashMap HashMap HashMap HashMap HashMap HashMap HashMap
13+
14+
15+
- 16 segments by default
16+
- Does not guarantee any ordering of keys
17+
18+
CASE 1: Two threads writing to different segments
19+
20+
KeyA.hash → Segment3
21+
KeyB.hash → Segment10
22+
23+
Thread A → put(KeyA)
24+
Thread B → put(KeyB)
25+
26+
KeyA → Segment3
27+
KeyB → Segment10
28+
29+
30+
Thread A
31+
|
32+
v
33+
Segment3 (LOCK)
34+
|
35+
v
36+
HashMap
37+
38+
39+
Thread B
40+
|
41+
v
42+
Segment10 (LOCK)
43+
|
44+
v
45+
HashMap
46+
47+
Segment3 lock ≠ Segment10 lock
48+
49+
Thread A and Thread B run simultaneously
50+
51+
52+
CASE 2: Two threads writing to the same segment
53+
54+
KeyA.hash → Segment3
55+
KeyB.hash → Segment3
56+
57+
Thread A → put(KeyA)
58+
Thread B → put(KeyB)
59+
60+
KeyA → Segment3
61+
KeyB → Segment3
62+
63+
Thread A
64+
|
65+
v
66+
Segment3 (LOCK ACQUIRED)
67+
|
68+
v
69+
HashMap
70+
71+
Thread B
72+
|
73+
v
74+
Segment3 (WAITING FOR LOCK)
75+
76+
Thread B must wait until Thread A releases lock
77+
*/
78+
79+
80+
81+
/*
82+
Map | Thread-safe | Sorted
83+
--------------------------------------------------
84+
HashMap | No | No
85+
ConcurrentHashMap | Yes | No
86+
TreeMap | No | Yes
87+
ConcurrentSkipListMap | Yes | Yes
88+
*/
89+
90+
public class ConcurrentHashMapDemo {
91+
public static void main(String[] args) {
92+
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
93+
// Java 7 --> segment based locking --> 16 segments --> smaller hashmaps
94+
// Only the segment being written to or read from is locked
95+
// read: do not require locking unless there is a write operation happening on the same segment
96+
// write: lock
97+
98+
// Java 8 --> no segmentation
99+
// --> Compare-And-Swap approach --> no locking except resizing or collision
100+
// Thread A last saw --> x = 42
101+
// Thread A work --> x to 50
102+
// if x is still 42, then change it to 50, else don't change and retry
103+
}
104+
}

0 commit comments

Comments
 (0)