Skip to content

Commit 5ef321f

Browse files
committed
feat: add ConcurrentSkipListMapDemo1 with string-key example
What - Created `ConcurrentSkipListMapDemo1` class. - Demonstrated `ConcurrentSkipListMap<String, Integer>` usage. - Inserted fruit names as keys and integers as values. - Printed map contents showing natural key ordering. Why - Extends prior demo by using `String` keys instead of `Integer`. - Highlights that `ConcurrentSkipListMap` maintains **lexicographic order** for strings. - Reinforces thread-safe + sorted map usage in simple scenarios. How - Initialized a `ConcurrentSkipListMap<String, Integer>`. - Added entries: `Apple=2`, `Banana=4`, `Mango=3`. - Printed output, which automatically sorts keys: `{Apple=2, Banana=4, Mango=3}`. Logic - Keys in `ConcurrentSkipListMap` are always kept sorted. - For `String` keys, natural ordering is lexicographic. - Thread-safe without needing external synchronization. Real-world applications - Useful for maintaining sorted dictionaries or lookup tables in concurrent environments. - Can efficiently support prefix-based queries or range operations with string keys. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent cdca1ac commit 5ef321f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.concurrent.ConcurrentSkipListMap;
2+
3+
/**
4+
* Demonstrates the usage of {@link ConcurrentSkipListMap}.
5+
6+
* <p>
7+
* Key points about ConcurrentSkipListMap:
8+
* <ul>
9+
* <li>A scalable concurrent implementation of {@code ConcurrentNavigableMap}.</li>
10+
* <li>MAP --> SORTED --> THREAD SAFE --> ConcurrentSkipListMap</li>
11+
* <li>Maintains keys in <b>sorted order</b> (natural ordering or a custom {@code Comparator}).</li>
12+
* <li>Internally implemented using a <b>concurrent variant of SkipLists</b>.</li>
13+
* <li>Provides expected average <b>O(log n)</b> time cost for operations like
14+
* {@code containsKey()}, {@code get()}, {@code put()}, and {@code remove()}.</li>
15+
* <li>Supports safe concurrent access — multiple threads can insert, remove,
16+
* update, or traverse without external synchronization.</li>
17+
* </ul>
18+
* </p>
19+
*/
20+
21+
public class ConcurrentSkipListMapDemo1 {
22+
public static void main(String[] args) {
23+
/* Create a ConcurrentSkipListMap.
24+
- Thread-safe
25+
- Maintains keys in sorted order
26+
*/
27+
ConcurrentSkipListMap<String, Integer> map = new ConcurrentSkipListMap<>();
28+
29+
// Insert key-value pairs into the map.
30+
map.put("Apple", 2);
31+
map.put("Banana", 4);
32+
map.put("Mango", 3);
33+
34+
/* Print the map.
35+
* Output will be sorted by keys (lexicographic order):
36+
* {Apple=2, Banana=4, Mango=3}
37+
*/
38+
System.out.println(map);
39+
}
40+
}

0 commit comments

Comments
 (0)