Download Jar. Libraryless. Click here for Pure Java version (1069L/8K).
1 | !7 |
2 | |
3 | static int n = 1000000; |
4 | |
5 | // iterate safely (& quickly) in the face of concurrent modifications |
6 | static <A, B> IterableIterator<A> iterateKeysQuickly(final NavigableMap<A, B> map) { |
7 | ret iteratorFromFunction(new F0<A>() { |
8 | Iterator<A> it = keys(map).iterator(); |
9 | A key; |
10 | |
11 | A get() { |
12 | synchronized(map) { |
13 | try { |
14 | if (!it.hasNext()) null; |
15 | ret key = it.next(); |
16 | } catch (ConcurrentModificationException e) { |
17 | print("Re-iterating"); |
18 | it = map.tailMap(key, false).keySet().iterator(); |
19 | if (!it.hasNext()) null; |
20 | ret key = it.next(); // Can't throw another exception |
21 | } |
22 | } |
23 | } |
24 | }); |
25 | } |
26 | |
27 | p { |
28 | final NavigableMap<S, Bool> map = synchroNavigableMap(litcimap()); |
29 | final new L<S> ids; |
30 | repeat n { |
31 | map.put(addAndReturn(ids, randomID()), Bool.TRUE); |
32 | } |
33 | |
34 | repeat 5 { |
35 | int i = 0; |
36 | long sum = 0; |
37 | time "Iterating" { |
38 | for (S key : keys(map)) { |
39 | if (!key.startsWith("_")) { |
40 | ++i; |
41 | sum += key.hashCode(); |
42 | } |
43 | } |
44 | } |
45 | assertEquals(i, n); |
46 | |
47 | i = 0; |
48 | long sum2 = 0; |
49 | time "Iterating quickly" { |
50 | for (S key : iterateKeysQuickly(map)) { |
51 | if (!key.startsWith("_")) { |
52 | ++i; |
53 | sum2 += key.hashCode(); |
54 | } |
55 | } |
56 | } |
57 | assertEquals(i, n); |
58 | assertEquals(sum, sum2); |
59 | } |
60 | } |
Began life as a copy of #1012166
download show line numbers debug dex old transpilations
Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #1012169 |
Snippet name: | Bench concurrency-safely iterating TreeMap faster [OK, just slightly slower than direct iteration] |
Eternal ID of this version: | #1012169/23 |
Text MD5: | 3a00171210f8a8a746a73c71774d8d20 |
Transpilation MD5: | 01a03cd2644cc0dd948b4b22c64c3822 |
Author: | stefan |
Category: | javax / collections |
Type: | JavaX source code (desktop) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2017-11-23 11:16:54 |
Source code size: | 1420 bytes / 60 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 500 / 1182 |
Version history: | 22 change(s) |
Referenced in: | [show references] |