Commit d9798be
committed
feat: add CopyOnWriteArraySet vs ConcurrentSkipListSet demo
What
- New demo `CopyOnWriteArraySetDemo` comparing two thread-safe `Set` implementations:
- `CopyOnWriteArraySet` (backed by `CopyOnWriteArrayList`).
- `ConcurrentSkipListSet` (concurrent, sorted set based on skip list).
Why
- Illustrates differences in iteration and modification behavior under concurrent-like patterns.
- Demonstrates how copy-on-write iterators remain unaffected by modifications, while skip-list iterators reflect changes.
How
- Created both sets and added integers 1–5.
- Iterated `CopyOnWriteArraySet` while adding element `6` → safe, but iterator does not see the modification until future iterations.
- Iterated `ConcurrentSkipListSet` while adding element `6` → safe, iterator reflects concurrent modifications and includes new element in iteration.
- Printed initial contents and iteration results.
Logic
- `CopyOnWriteArraySet`:
- Snapshot semantics for iterators → modifications create new underlying array copies, no `ConcurrentModificationException`.
- No duplicates allowed.
- `ConcurrentSkipListSet`:
- Lock-free, concurrent skip list implementation.
- Iterators are weakly consistent → may reflect modifications made during traversal.
Applications
- Use `CopyOnWriteArraySet` for small, mostly-read sets where iteration speed and consistency matter more than mutation performance.
- Use `ConcurrentSkipListSet` for sorted sets under heavy concurrent updates where you want modifications visible during traversal.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d04cccc commit d9798be
File tree
1 file changed
+15
-11
lines changed- Section 25 Collections Frameworks/List Interface/Copy On Write ArrayList/src
1 file changed
+15
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
7 | 5 | | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
| 6 | + | |
12 | 7 | | |
13 | 8 | | |
| 9 | + | |
14 | 10 | | |
15 | 11 | | |
16 | 12 | | |
| |||
19 | 15 | | |
20 | 16 | | |
21 | 17 | | |
| 18 | + | |
22 | 19 | | |
23 | 20 | | |
24 | 21 | | |
25 | | - | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
26 | 25 | | |
| 26 | + | |
27 | 27 | | |
28 | 28 | | |
29 | 29 | | |
30 | | - | |
| 30 | + | |
| 31 | + | |
31 | 32 | | |
32 | 33 | | |
33 | | - | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
34 | 37 | | |
| 38 | + | |
35 | 39 | | |
36 | | - | |
| 40 | + | |
37 | 41 | | |
38 | | - | |
39 | 42 | | |
40 | 43 | | |
| 44 | + | |
0 commit comments