1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
import java.util.*; |
9 |
import java.util.stream.Stream; |
10 |
import java.util.Spliterator; |
11 |
import java.util.stream.Streams; |
12 |
import java.util.function.Consumer; |
13 |
|
14 |
|
15 |
/** |
16 |
* A scalable concurrent {@link ConcurrentNavigableMap} implementation. |
17 |
* The map is sorted according to the {@linkplain Comparable natural |
18 |
* ordering} of its keys, or by a {@link Comparator} provided at map |
19 |
* creation time, depending on which constructor is used. |
20 |
* |
21 |
* <p>This class implements a concurrent variant of <a |
22 |
* href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a> |
23 |
* providing expected average <i>log(n)</i> time cost for the |
24 |
* {@code containsKey}, {@code get}, {@code put} and |
25 |
* {@code remove} operations and their variants. Insertion, removal, |
26 |
* update, and access operations safely execute concurrently by |
27 |
* multiple threads. Iterators are <i>weakly consistent</i>, returning |
28 |
* elements reflecting the state of the map at some point at or since |
29 |
* the creation of the iterator. They do <em>not</em> throw {@link |
30 |
* ConcurrentModificationException}, and may proceed concurrently with |
31 |
* other operations. Ascending key ordered views and their iterators |
32 |
* are faster than descending ones. |
33 |
* |
34 |
* <p>All {@code Map.Entry} pairs returned by methods in this class |
35 |
* and its views represent snapshots of mappings at the time they were |
36 |
* produced. They do <em>not</em> support the {@code Entry.setValue} |
37 |
* method. (Note however that it is possible to change mappings in the |
38 |
* associated map using {@code put}, {@code putIfAbsent}, or |
39 |
* {@code replace}, depending on exactly which effect you need.) |
40 |
* |
41 |
* <p>Beware that, unlike in most collections, the {@code size} |
42 |
* method is <em>not</em> a constant-time operation. Because of the |
43 |
* asynchronous nature of these maps, determining the current number |
44 |
* of elements requires a traversal of the elements, and so may report |
45 |
* inaccurate results if this collection is modified during traversal. |
46 |
* Additionally, the bulk operations {@code putAll}, {@code equals}, |
47 |
* {@code toArray}, {@code containsValue}, and {@code clear} are |
48 |
* <em>not</em> guaranteed to be performed atomically. For example, an |
49 |
* iterator operating concurrently with a {@code putAll} operation |
50 |
* might view only some of the added elements. |
51 |
* |
52 |
* <p>This class and its views and iterators implement all of the |
53 |
* <em>optional</em> methods of the {@link Map} and {@link Iterator} |
54 |
* interfaces. Like most other concurrent collections, this class does |
55 |
* <em>not</em> permit the use of {@code null} keys or values because some |
56 |
* null return values cannot be reliably distinguished from the absence of |
57 |
* elements. |
58 |
* |
59 |
* <p>A {@link Set} projection of a ConcurrentSkipListMap may be |
60 |
* created (using {@link #newKeySet()}), or viewed (using {@link |
61 |
* #keySet(Object)} when only keys are of interest, and the mapped |
62 |
* values are (perhaps transiently) not used or all take the same |
63 |
* mapping value. |
64 |
* |
65 |
* <p>This class is a member of the |
66 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
67 |
* Java Collections Framework</a>. |
68 |
* |
69 |
* @author Doug Lea |
70 |
* @param <K> the type of keys maintained by this map |
71 |
* @param <V> the type of mapped values |
72 |
* @since 1.6 |
73 |
*/ |
74 |
@SuppressWarnings("unchecked") |
75 |
public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V> |
76 |
implements ConcurrentNavigableMap<K,V>, |
77 |
Cloneable, |
78 |
java.io.Serializable { |
79 |
/* |
80 |
* This class implements a tree-like two-dimensionally linked skip |
81 |
* list in which the index levels are represented in separate |
82 |
* nodes from the base nodes holding data. There are two reasons |
83 |
* for taking this approach instead of the usual array-based |
84 |
* structure: 1) Array based implementations seem to encounter |
85 |
* more complexity and overhead 2) We can use cheaper algorithms |
86 |
* for the heavily-traversed index lists than can be used for the |
87 |
* base lists. Here's a picture of some of the basics for a |
88 |
* possible list with 2 levels of index: |
89 |
* |
90 |
* Head nodes Index nodes |
91 |
* +-+ right +-+ +-+ |
92 |
* |2|---------------->| |--------------------->| |->null |
93 |
* +-+ +-+ +-+ |
94 |
* | down | | |
95 |
* v v v |
96 |
* +-+ +-+ +-+ +-+ +-+ +-+ |
97 |
* |1|----------->| |->| |------>| |----------->| |------>| |->null |
98 |
* +-+ +-+ +-+ +-+ +-+ +-+ |
99 |
* v | | | | | |
100 |
* Nodes next v v v v v |
101 |
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ |
102 |
* | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null |
103 |
* +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ |
104 |
* |
105 |
* The base lists use a variant of the HM linked ordered set |
106 |
* algorithm. See Tim Harris, "A pragmatic implementation of |
107 |
* non-blocking linked lists" |
108 |
* http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged |
109 |
* Michael "High Performance Dynamic Lock-Free Hash Tables and |
110 |
* List-Based Sets" |
111 |
* http://www.research.ibm.com/people/m/michael/pubs.htm. The |
112 |
* basic idea in these lists is to mark the "next" pointers of |
113 |
* deleted nodes when deleting to avoid conflicts with concurrent |
114 |
* insertions, and when traversing to keep track of triples |
115 |
* (predecessor, node, successor) in order to detect when and how |
116 |
* to unlink these deleted nodes. |
117 |
* |
118 |
* Rather than using mark-bits to mark list deletions (which can |
119 |
* be slow and space-intensive using AtomicMarkedReference), nodes |
120 |
* use direct CAS'able next pointers. On deletion, instead of |
121 |
* marking a pointer, they splice in another node that can be |
122 |
* thought of as standing for a marked pointer (indicating this by |
123 |
* using otherwise impossible field values). Using plain nodes |
124 |
* acts roughly like "boxed" implementations of marked pointers, |
125 |
* but uses new nodes only when nodes are deleted, not for every |
126 |
* link. This requires less space and supports faster |
127 |
* traversal. Even if marked references were better supported by |
128 |
* JVMs, traversal using this technique might still be faster |
129 |
* because any search need only read ahead one more node than |
130 |
* otherwise required (to check for trailing marker) rather than |
131 |
* unmasking mark bits or whatever on each read. |
132 |
* |
133 |
* This approach maintains the essential property needed in the HM |
134 |
* algorithm of changing the next-pointer of a deleted node so |
135 |
* that any other CAS of it will fail, but implements the idea by |
136 |
* changing the pointer to point to a different node, not by |
137 |
* marking it. While it would be possible to further squeeze |
138 |
* space by defining marker nodes not to have key/value fields, it |
139 |
* isn't worth the extra type-testing overhead. The deletion |
140 |
* markers are rarely encountered during traversal and are |
141 |
* normally quickly garbage collected. (Note that this technique |
142 |
* would not work well in systems without garbage collection.) |
143 |
* |
144 |
* In addition to using deletion markers, the lists also use |
145 |
* nullness of value fields to indicate deletion, in a style |
146 |
* similar to typical lazy-deletion schemes. If a node's value is |
147 |
* null, then it is considered logically deleted and ignored even |
148 |
* though it is still reachable. This maintains proper control of |
149 |
* concurrent replace vs delete operations -- an attempted replace |
150 |
* must fail if a delete beat it by nulling field, and a delete |
151 |
* must return the last non-null value held in the field. (Note: |
152 |
* Null, rather than some special marker, is used for value fields |
153 |
* here because it just so happens to mesh with the Map API |
154 |
* requirement that method get returns null if there is no |
155 |
* mapping, which allows nodes to remain concurrently readable |
156 |
* even when deleted. Using any other marker value here would be |
157 |
* messy at best.) |
158 |
* |
159 |
* Here's the sequence of events for a deletion of node n with |
160 |
* predecessor b and successor f, initially: |
161 |
* |
162 |
* +------+ +------+ +------+ |
163 |
* ... | b |------>| n |----->| f | ... |
164 |
* +------+ +------+ +------+ |
165 |
* |
166 |
* 1. CAS n's value field from non-null to null. |
167 |
* From this point on, no public operations encountering |
168 |
* the node consider this mapping to exist. However, other |
169 |
* ongoing insertions and deletions might still modify |
170 |
* n's next pointer. |
171 |
* |
172 |
* 2. CAS n's next pointer to point to a new marker node. |
173 |
* From this point on, no other nodes can be appended to n. |
174 |
* which avoids deletion errors in CAS-based linked lists. |
175 |
* |
176 |
* +------+ +------+ +------+ +------+ |
177 |
* ... | b |------>| n |----->|marker|------>| f | ... |
178 |
* +------+ +------+ +------+ +------+ |
179 |
* |
180 |
* 3. CAS b's next pointer over both n and its marker. |
181 |
* From this point on, no new traversals will encounter n, |
182 |
* and it can eventually be GCed. |
183 |
* +------+ +------+ |
184 |
* ... | b |----------------------------------->| f | ... |
185 |
* +------+ +------+ |
186 |
* |
187 |
* A failure at step 1 leads to simple retry due to a lost race |
188 |
* with another operation. Steps 2-3 can fail because some other |
189 |
* thread noticed during a traversal a node with null value and |
190 |
* helped out by marking and/or unlinking. This helping-out |
191 |
* ensures that no thread can become stuck waiting for progress of |
192 |
* the deleting thread. The use of marker nodes slightly |
193 |
* complicates helping-out code because traversals must track |
194 |
* consistent reads of up to four nodes (b, n, marker, f), not |
195 |
* just (b, n, f), although the next field of a marker is |
196 |
* immutable, and once a next field is CAS'ed to point to a |
197 |
* marker, it never again changes, so this requires less care. |
198 |
* |
199 |
* Skip lists add indexing to this scheme, so that the base-level |
200 |
* traversals start close to the locations being found, inserted |
201 |
* or deleted -- usually base level traversals only traverse a few |
202 |
* nodes. This doesn't change the basic algorithm except for the |
203 |
* need to make sure base traversals start at predecessors (here, |
204 |
* b) that are not (structurally) deleted, otherwise retrying |
205 |
* after processing the deletion. |
206 |
* |
207 |
* Index levels are maintained as lists with volatile next fields, |
208 |
* using CAS to link and unlink. Races are allowed in index-list |
209 |
* operations that can (rarely) fail to link in a new index node |
210 |
* or delete one. (We can't do this of course for data nodes.) |
211 |
* However, even when this happens, the index lists remain sorted, |
212 |
* so correctly serve as indices. This can impact performance, |
213 |
* but since skip lists are probabilistic anyway, the net result |
214 |
* is that under contention, the effective "p" value may be lower |
215 |
* than its nominal value. And race windows are kept small enough |
216 |
* that in practice these failures are rare, even under a lot of |
217 |
* contention. |
218 |
* |
219 |
* The fact that retries (for both base and index lists) are |
220 |
* relatively cheap due to indexing allows some minor |
221 |
* simplifications of retry logic. Traversal restarts are |
222 |
* performed after most "helping-out" CASes. This isn't always |
223 |
* strictly necessary, but the implicit backoffs tend to help |
224 |
* reduce other downstream failed CAS's enough to outweigh restart |
225 |
* cost. This worsens the worst case, but seems to improve even |
226 |
* highly contended cases. |
227 |
* |
228 |
* Unlike most skip-list implementations, index insertion and |
229 |
* deletion here require a separate traversal pass occuring after |
230 |
* the base-level action, to add or remove index nodes. This adds |
231 |
* to single-threaded overhead, but improves contended |
232 |
* multithreaded performance by narrowing interference windows, |
233 |
* and allows deletion to ensure that all index nodes will be made |
234 |
* unreachable upon return from a public remove operation, thus |
235 |
* avoiding unwanted garbage retention. This is more important |
236 |
* here than in some other data structures because we cannot null |
237 |
* out node fields referencing user keys since they might still be |
238 |
* read by other ongoing traversals. |
239 |
* |
240 |
* Indexing uses skip list parameters that maintain good search |
241 |
* performance while using sparser-than-usual indices: The |
242 |
* hardwired parameters k=1, p=0.5 (see method addIndex) mean |
243 |
* that about one-quarter of the nodes have indices. Of those that |
244 |
* do, half have one level, a quarter have two, and so on (see |
245 |
* Pugh's Skip List Cookbook, sec 3.4). The expected total space |
246 |
* requirement for a map is slightly less than for the current |
247 |
* implementation of java.util.TreeMap. |
248 |
* |
249 |
* Changing the level of the index (i.e, the height of the |
250 |
* tree-like structure) also uses CAS. The head index has initial |
251 |
* level/height of one. Creation of an index with height greater |
252 |
* than the current level adds a level to the head index by |
253 |
* CAS'ing on a new top-most head. To maintain good performance |
254 |
* after a lot of removals, deletion methods heuristically try to |
255 |
* reduce the height if the topmost levels appear to be empty. |
256 |
* This may encounter races in which it possible (but rare) to |
257 |
* reduce and "lose" a level just as it is about to contain an |
258 |
* index (that will then never be encountered). This does no |
259 |
* structural harm, and in practice appears to be a better option |
260 |
* than allowing unrestrained growth of levels. |
261 |
* |
262 |
* The code for all this is more verbose than you'd like. Most |
263 |
* operations entail locating an element (or position to insert an |
264 |
* element). The code to do this can't be nicely factored out |
265 |
* because subsequent uses require a snapshot of predecessor |
266 |
* and/or successor and/or value fields which can't be returned |
267 |
* all at once, at least not without creating yet another object |
268 |
* to hold them -- creating such little objects is an especially |
269 |
* bad idea for basic internal search operations because it adds |
270 |
* to GC overhead. (This is one of the few times I've wished Java |
271 |
* had macros.) Instead, some traversal code is interleaved within |
272 |
* insertion and removal operations. The control logic to handle |
273 |
* all the retry conditions is sometimes twisty. Most search is |
274 |
* broken into 2 parts. findPredecessor() searches index nodes |
275 |
* only, returning a base-level predecessor of the key. findNode() |
276 |
* finishes out the base-level search. Even with this factoring, |
277 |
* there is a fair amount of near-duplication of code to handle |
278 |
* variants. |
279 |
* |
280 |
* To produce random values without interference across threads, |
281 |
* we use within-JDK thread local random support (via the |
282 |
* "secondary seed", to avoid interference with user-level |
283 |
* ThreadLocalRandom.) |
284 |
* |
285 |
* A previous version of this class wrapped non-comparable keys |
286 |
* with their comparators to emulate Comparables when using |
287 |
* comparators vs Comparables. This saved the need to choose |
288 |
* among the unpleasant options of either possibly re-reading a |
289 |
* comparator on each comparison (which suffers when among all of |
290 |
* the volatile read snapshots) versus code duplication, at the |
291 |
* cost of usually requiring an object construction per operation |
292 |
* when not naturally ordered. However, as usage evolves, use of |
293 |
* comparators has become more common, so we have to settle for |
294 |
* code duplication as the lesser evil. Thus, there are "xxxCmp" |
295 |
* versions of many of the xxx methods, all bundled later in this |
296 |
* file. |
297 |
* |
298 |
* For explanation of algorithms sharing at least a couple of |
299 |
* features with this one, see Mikhail Fomitchev's thesis |
300 |
* (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis |
301 |
* (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's |
302 |
* thesis (http://www.cs.chalmers.se/~phs/). |
303 |
* |
304 |
* Given the use of tree-like index nodes, you might wonder why |
305 |
* this doesn't use some kind of search tree instead, which would |
306 |
* support somewhat faster search operations. The reason is that |
307 |
* there are no known efficient lock-free insertion and deletion |
308 |
* algorithms for search trees. The immutability of the "down" |
309 |
* links of index nodes (as opposed to mutable "left" fields in |
310 |
* true trees) makes this tractable using only CAS operations. |
311 |
* |
312 |
* Notation guide for local variables |
313 |
* Node: b, n, f for predecessor, node, successor |
314 |
* Index: q, r, d for index node, right, down. |
315 |
* t for another index node |
316 |
* Head: h |
317 |
* Levels: j |
318 |
* Keys: k, key |
319 |
* Values: v, value |
320 |
* Comparisons: c |
321 |
*/ |
322 |
|
323 |
private static final long serialVersionUID = -8627078645895051609L; |
324 |
|
325 |
/** |
326 |
* Special value used to identify base-level header |
327 |
*/ |
328 |
private static final Object BASE_HEADER = new Object(); |
329 |
|
330 |
/** |
331 |
* The topmost head index of the skiplist. |
332 |
*/ |
333 |
private transient volatile HeadIndex<K,V> head; |
334 |
|
335 |
/** |
336 |
* The comparator used to maintain order in this map, or null |
337 |
* if using natural ordering. |
338 |
* @serial |
339 |
*/ |
340 |
private final Comparator<? super K> comparator; |
341 |
|
342 |
/** Lazily initialized key set */ |
343 |
private transient KeySetView<K,V> keySet; |
344 |
/** Lazily initialized entry set */ |
345 |
private transient EntrySet<K,V> entrySet; |
346 |
/** Lazily initialized values collection */ |
347 |
private transient Values<V> values; |
348 |
/** Lazily initialized descending key set */ |
349 |
private transient ConcurrentNavigableMap<K,V> descendingMap; |
350 |
|
351 |
/** |
352 |
* Initializes or resets state. Needed by constructors, clone, |
353 |
* clear, readObject. and ConcurrentSkipListSet.clone. |
354 |
* (Note that comparator must be separately initialized.) |
355 |
*/ |
356 |
final void initialize() { |
357 |
keySet = null; |
358 |
entrySet = null; |
359 |
values = null; |
360 |
descendingMap = null; |
361 |
head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null), |
362 |
null, null, 1); |
363 |
} |
364 |
|
365 |
/** |
366 |
* compareAndSet head node |
367 |
*/ |
368 |
private boolean casHead(HeadIndex<K,V> cmp, HeadIndex<K,V> val) { |
369 |
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); |
370 |
} |
371 |
|
372 |
/* ---------------- Nodes -------------- */ |
373 |
|
374 |
/** |
375 |
* Nodes hold keys and values, and are singly linked in sorted |
376 |
* order, possibly with some intervening marker nodes. The list is |
377 |
* headed by a dummy node accessible as head.node. The value field |
378 |
* is declared only as Object because it takes special non-V |
379 |
* values for marker and header nodes. |
380 |
*/ |
381 |
static final class Node<K,V> { |
382 |
final K key; |
383 |
volatile Object value; |
384 |
volatile Node<K,V> next; |
385 |
|
386 |
/** |
387 |
* Creates a new regular node. |
388 |
*/ |
389 |
Node(K key, Object value, Node<K,V> next) { |
390 |
this.key = key; |
391 |
this.value = value; |
392 |
this.next = next; |
393 |
} |
394 |
|
395 |
/** |
396 |
* Creates a new marker node. A marker is distinguished by |
397 |
* having its value field point to itself. Marker nodes also |
398 |
* have null keys, a fact that is exploited in a few places, |
399 |
* but this doesn't distinguish markers from the base-level |
400 |
* header node (head.node), which also has a null key. |
401 |
*/ |
402 |
Node(Node<K,V> next) { |
403 |
this.key = null; |
404 |
this.value = this; |
405 |
this.next = next; |
406 |
} |
407 |
|
408 |
/** |
409 |
* compareAndSet value field |
410 |
*/ |
411 |
boolean casValue(Object cmp, Object val) { |
412 |
return UNSAFE.compareAndSwapObject(this, valueOffset, cmp, val); |
413 |
} |
414 |
|
415 |
/** |
416 |
* compareAndSet next field |
417 |
*/ |
418 |
boolean casNext(Node<K,V> cmp, Node<K,V> val) { |
419 |
return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); |
420 |
} |
421 |
|
422 |
/** |
423 |
* Returns true if this node is a marker. This method isn't |
424 |
* actually called in any current code checking for markers |
425 |
* because callers will have already read value field and need |
426 |
* to use that read (not another done here) and so directly |
427 |
* test if value points to node. |
428 |
* |
429 |
* @return true if this node is a marker node |
430 |
*/ |
431 |
boolean isMarker() { |
432 |
return value == this; |
433 |
} |
434 |
|
435 |
/** |
436 |
* Returns true if this node is the header of base-level list. |
437 |
* @return true if this node is header node |
438 |
*/ |
439 |
boolean isBaseHeader() { |
440 |
return value == BASE_HEADER; |
441 |
} |
442 |
|
443 |
/** |
444 |
* Tries to append a deletion marker to this node. |
445 |
* @param f the assumed current successor of this node |
446 |
* @return true if successful |
447 |
*/ |
448 |
boolean appendMarker(Node<K,V> f) { |
449 |
return casNext(f, new Node<K,V>(f)); |
450 |
} |
451 |
|
452 |
/** |
453 |
* Helps out a deletion by appending marker or unlinking from |
454 |
* predecessor. This is called during traversals when value |
455 |
* field seen to be null. |
456 |
* @param b predecessor |
457 |
* @param f successor |
458 |
*/ |
459 |
void helpDelete(Node<K,V> b, Node<K,V> f) { |
460 |
/* |
461 |
* Rechecking links and then doing only one of the |
462 |
* help-out stages per call tends to minimize CAS |
463 |
* interference among helping threads. |
464 |
*/ |
465 |
if (f == next && this == b.next) { |
466 |
if (f == null || f.value != f) // not already marked |
467 |
appendMarker(f); |
468 |
else |
469 |
b.casNext(this, f.next); |
470 |
} |
471 |
} |
472 |
|
473 |
/** |
474 |
* Returns value if this node contains a valid key-value pair, |
475 |
* else null. |
476 |
* @return this node's value if it isn't a marker or header or |
477 |
* is deleted, else null |
478 |
*/ |
479 |
V getValidValue() { |
480 |
Object v = value; |
481 |
if (v == this || v == BASE_HEADER) |
482 |
return null; |
483 |
return (V)v; |
484 |
} |
485 |
|
486 |
/** |
487 |
* Creates and returns a new SimpleImmutableEntry holding current |
488 |
* mapping if this node holds a valid value, else null. |
489 |
* @return new entry or null |
490 |
*/ |
491 |
AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() { |
492 |
V v = getValidValue(); |
493 |
if (v == null) |
494 |
return null; |
495 |
return new AbstractMap.SimpleImmutableEntry<K,V>(key, v); |
496 |
} |
497 |
|
498 |
// UNSAFE mechanics |
499 |
|
500 |
private static final sun.misc.Unsafe UNSAFE; |
501 |
private static final long valueOffset; |
502 |
private static final long nextOffset; |
503 |
|
504 |
static { |
505 |
try { |
506 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
507 |
Class<?> k = Node.class; |
508 |
valueOffset = UNSAFE.objectFieldOffset |
509 |
(k.getDeclaredField("value")); |
510 |
nextOffset = UNSAFE.objectFieldOffset |
511 |
(k.getDeclaredField("next")); |
512 |
} catch (Exception e) { |
513 |
throw new Error(e); |
514 |
} |
515 |
} |
516 |
} |
517 |
|
518 |
/* ---------------- Indexing -------------- */ |
519 |
|
520 |
/** |
521 |
* Index nodes represent the levels of the skip list. Note that |
522 |
* even though both Nodes and Indexes have forward-pointing |
523 |
* fields, they have different types and are handled in different |
524 |
* ways, that can't nicely be captured by placing field in a |
525 |
* shared abstract class. |
526 |
*/ |
527 |
static class Index<K,V> { |
528 |
final Node<K,V> node; |
529 |
final Index<K,V> down; |
530 |
volatile Index<K,V> right; |
531 |
|
532 |
/** |
533 |
* Creates index node with given values. |
534 |
*/ |
535 |
Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) { |
536 |
this.node = node; |
537 |
this.down = down; |
538 |
this.right = right; |
539 |
} |
540 |
|
541 |
/** |
542 |
* compareAndSet right field |
543 |
*/ |
544 |
final boolean casRight(Index<K,V> cmp, Index<K,V> val) { |
545 |
return UNSAFE.compareAndSwapObject(this, rightOffset, cmp, val); |
546 |
} |
547 |
|
548 |
/** |
549 |
* Returns true if the node this indexes has been deleted. |
550 |
* @return true if indexed node is known to be deleted |
551 |
*/ |
552 |
final boolean indexesDeletedNode() { |
553 |
return node.value == null; |
554 |
} |
555 |
|
556 |
/** |
557 |
* Tries to CAS newSucc as successor. To minimize races with |
558 |
* unlink that may lose this index node, if the node being |
559 |
* indexed is known to be deleted, it doesn't try to link in. |
560 |
* @param succ the expected current successor |
561 |
* @param newSucc the new successor |
562 |
* @return true if successful |
563 |
*/ |
564 |
final boolean link(Index<K,V> succ, Index<K,V> newSucc) { |
565 |
Node<K,V> n = node; |
566 |
newSucc.right = succ; |
567 |
return n.value != null && casRight(succ, newSucc); |
568 |
} |
569 |
|
570 |
/** |
571 |
* Tries to CAS right field to skip over apparent successor |
572 |
* succ. Fails (forcing a retraversal by caller) if this node |
573 |
* is known to be deleted. |
574 |
* @param succ the expected current successor |
575 |
* @return true if successful |
576 |
*/ |
577 |
final boolean unlink(Index<K,V> succ) { |
578 |
return !indexesDeletedNode() && casRight(succ, succ.right); |
579 |
} |
580 |
|
581 |
// Unsafe mechanics |
582 |
private static final sun.misc.Unsafe UNSAFE; |
583 |
private static final long rightOffset; |
584 |
static { |
585 |
try { |
586 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
587 |
Class<?> k = Index.class; |
588 |
rightOffset = UNSAFE.objectFieldOffset |
589 |
(k.getDeclaredField("right")); |
590 |
} catch (Exception e) { |
591 |
throw new Error(e); |
592 |
} |
593 |
} |
594 |
} |
595 |
|
596 |
/* ---------------- Head nodes -------------- */ |
597 |
|
598 |
/** |
599 |
* Nodes heading each level keep track of their level. |
600 |
*/ |
601 |
static final class HeadIndex<K,V> extends Index<K,V> { |
602 |
final int level; |
603 |
HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) { |
604 |
super(node, down, right); |
605 |
this.level = level; |
606 |
} |
607 |
} |
608 |
|
609 |
/* ---------------- Comparison utilities -------------- */ |
610 |
|
611 |
/** |
612 |
* Compares using comparator or natural ordering. Used in cases |
613 |
* where it isn't worthwhile to use multiple code paths. |
614 |
*/ |
615 |
int compare(K k1, K k2) throws ClassCastException { |
616 |
Comparator<? super K> cmp = comparator; |
617 |
if (cmp != null) |
618 |
return cmp.compare(k1, k2); |
619 |
else |
620 |
return ((Comparable<? super K>)k1).compareTo(k2); |
621 |
} |
622 |
|
623 |
/** |
624 |
* Returns true if given key greater than or equal to least and |
625 |
* strictly less than fence, bypassing either test if least or |
626 |
* fence are null. Needed mainly in submap operations. |
627 |
*/ |
628 |
boolean inHalfOpenRange(K key, K least, K fence) { |
629 |
if (key == null) |
630 |
throw new NullPointerException(); |
631 |
return ((least == null || compare(key, least) >= 0) && |
632 |
(fence == null || compare(key, fence) < 0)); |
633 |
} |
634 |
|
635 |
/** |
636 |
* Returns true if given key greater than or equal to least and less |
637 |
* or equal to fence. Needed mainly in submap operations. |
638 |
*/ |
639 |
boolean inOpenRange(K key, K least, K fence) { |
640 |
if (key == null) |
641 |
throw new NullPointerException(); |
642 |
return ((least == null || compare(key, least) >= 0) && |
643 |
(fence == null || compare(key, fence) <= 0)); |
644 |
} |
645 |
|
646 |
/* ---------------- Traversal -------------- */ |
647 |
|
648 |
/** |
649 |
* Returns a base-level node with key strictly less than given key, |
650 |
* or the base-level header if there is no such node. Also |
651 |
* unlinks indexes to deleted nodes found along the way. Callers |
652 |
* rely on this side-effect of clearing indices to deleted nodes. |
653 |
* @param key the key |
654 |
* @return a predecessor of key |
655 |
*/ |
656 |
private Node<K,V> findPredecessor(Comparable<? super K> key) { |
657 |
if (key == null) |
658 |
throw new NullPointerException(); // don't postpone errors |
659 |
for (;;) { |
660 |
Index<K,V> q = head; |
661 |
Index<K,V> r = q.right; |
662 |
for (;;) { |
663 |
if (r != null) { |
664 |
Node<K,V> n = r.node; |
665 |
K k = n.key; |
666 |
if (n.value == null) { |
667 |
if (!q.unlink(r)) |
668 |
break; // restart |
669 |
r = q.right; // reread r |
670 |
continue; |
671 |
} |
672 |
if (key.compareTo(k) > 0) { |
673 |
q = r; |
674 |
r = r.right; |
675 |
continue; |
676 |
} |
677 |
} |
678 |
Index<K,V> d = q.down; |
679 |
if (d != null) { |
680 |
q = d; |
681 |
r = d.right; |
682 |
} else |
683 |
return q.node; |
684 |
} |
685 |
} |
686 |
} |
687 |
|
688 |
/** |
689 |
* Returns node holding key or null if no such, clearing out any |
690 |
* deleted nodes seen along the way. Repeatedly traverses at |
691 |
* base-level looking for key starting at predecessor returned |
692 |
* from findPredecessor, processing base-level deletions as |
693 |
* encountered. Some callers rely on this side-effect of clearing |
694 |
* deleted nodes. |
695 |
* |
696 |
* Restarts occur, at traversal step centered on node n, if: |
697 |
* |
698 |
* (1) After reading n's next field, n is no longer assumed |
699 |
* predecessor b's current successor, which means that |
700 |
* we don't have a consistent 3-node snapshot and so cannot |
701 |
* unlink any subsequent deleted nodes encountered. |
702 |
* |
703 |
* (2) n's value field is null, indicating n is deleted, in |
704 |
* which case we help out an ongoing structural deletion |
705 |
* before retrying. Even though there are cases where such |
706 |
* unlinking doesn't require restart, they aren't sorted out |
707 |
* here because doing so would not usually outweigh cost of |
708 |
* restarting. |
709 |
* |
710 |
* (3) n is a marker or n's predecessor's value field is null, |
711 |
* indicating (among other possibilities) that |
712 |
* findPredecessor returned a deleted node. We can't unlink |
713 |
* the node because we don't know its predecessor, so rely |
714 |
* on another call to findPredecessor to notice and return |
715 |
* some earlier predecessor, which it will do. This check is |
716 |
* only strictly needed at beginning of loop, (and the |
717 |
* b.value check isn't strictly needed at all) but is done |
718 |
* each iteration to help avoid contention with other |
719 |
* threads by callers that will fail to be able to change |
720 |
* links, and so will retry anyway. |
721 |
* |
722 |
* The traversal loops in doPut, doRemove, and findNear all |
723 |
* include the same three kinds of checks. And specialized |
724 |
* versions appear in findFirst, and findLast and their |
725 |
* variants. They can't easily share code because each uses the |
726 |
* reads of fields held in locals occurring in the orders they |
727 |
* were performed. |
728 |
* |
729 |
* @param key the key |
730 |
* @return node holding key, or null if no such |
731 |
*/ |
732 |
private Node<K,V> findNode(Comparable<? super K> key) { |
733 |
if (key == null) |
734 |
throw new NullPointerException(); // don't postpone errors |
735 |
for (;;) { |
736 |
Node<K,V> b = findPredecessor(key); |
737 |
Node<K,V> n = b.next; |
738 |
for (;;) { |
739 |
if (n == null) |
740 |
return null; |
741 |
Node<K,V> f = n.next; |
742 |
if (n != b.next) // inconsistent read |
743 |
break; |
744 |
Object v = n.value; |
745 |
if (v == null) { // n is deleted |
746 |
n.helpDelete(b, f); |
747 |
break; |
748 |
} |
749 |
if (v == n || b.value == null) // b is deleted |
750 |
break; |
751 |
int c = key.compareTo(n.key); |
752 |
if (c == 0) |
753 |
return n; |
754 |
if (c < 0) |
755 |
return null; |
756 |
b = n; |
757 |
n = f; |
758 |
} |
759 |
} |
760 |
} |
761 |
|
762 |
/** |
763 |
* Gets value for key. Almost the same as findNode, but returns |
764 |
* the found value (to avoid retries during re-reads) |
765 |
* |
766 |
* @param okey the key |
767 |
* @return the value, or null if absent |
768 |
*/ |
769 |
private V doGet(Object okey) { |
770 |
if (okey == null) |
771 |
throw new NullPointerException(); |
772 |
@SuppressWarnings("unchecked") Comparable<? super K> key = |
773 |
(Comparable<? super K>)okey; |
774 |
for (;;) { |
775 |
Node<K,V> b = findPredecessor(key); |
776 |
Node<K,V> n = b.next; |
777 |
for (;;) { |
778 |
if (n == null) |
779 |
return null; |
780 |
Node<K,V> f = n.next; |
781 |
if (n != b.next) // inconsistent read |
782 |
break; |
783 |
Object v = n.value; |
784 |
if (v == null) { // n is deleted |
785 |
n.helpDelete(b, f); |
786 |
break; |
787 |
} |
788 |
if (v == n || b.value == null) // b is deleted |
789 |
break; |
790 |
int c = key.compareTo(n.key); |
791 |
if (c == 0) |
792 |
return (V)v; |
793 |
if (c < 0) |
794 |
return null; |
795 |
b = n; |
796 |
n = f; |
797 |
} |
798 |
} |
799 |
} |
800 |
|
801 |
|
802 |
/* ---------------- Insertion -------------- */ |
803 |
|
804 |
/** |
805 |
* Main insertion method. Adds element if not present, or |
806 |
* replaces value if present and onlyIfAbsent is false. |
807 |
* @param kkey the key |
808 |
* @param value the value that must be associated with key |
809 |
* @param onlyIfAbsent if should not insert if already present |
810 |
* @return the old value, or null if newly inserted |
811 |
*/ |
812 |
private V doPut(K kkey, V value, boolean onlyIfAbsent) { |
813 |
if (kkey == null) |
814 |
throw new NullPointerException(); |
815 |
@SuppressWarnings("unchecked") Comparable<? super K> key = |
816 |
(Comparable<? super K>)kkey; |
817 |
for (;;) { |
818 |
Node<K,V> b = findPredecessor(key); |
819 |
Node<K,V> n = b.next; |
820 |
for (;;) { |
821 |
if (n != null) { |
822 |
Node<K,V> f = n.next; |
823 |
if (n != b.next) // inconsistent read |
824 |
break; |
825 |
Object v = n.value; |
826 |
if (v == null) { // n is deleted |
827 |
n.helpDelete(b, f); |
828 |
break; |
829 |
} |
830 |
if (v == n || b.value == null) // b is deleted |
831 |
break; |
832 |
int c = key.compareTo(n.key); |
833 |
if (c > 0) { |
834 |
b = n; |
835 |
n = f; |
836 |
continue; |
837 |
} |
838 |
if (c == 0) { |
839 |
if (onlyIfAbsent || n.casValue(v, value)) |
840 |
return (V)v; |
841 |
else |
842 |
break; // restart if lost race to replace value |
843 |
} |
844 |
// else c < 0; fall through |
845 |
} |
846 |
|
847 |
Node<K,V> z = new Node<K,V>(kkey, value, n); |
848 |
if (!b.casNext(n, z)) |
849 |
break; // restart if lost race to append to b |
850 |
addIndex(kkey, z); |
851 |
return null; |
852 |
} |
853 |
} |
854 |
} |
855 |
|
856 |
/** |
857 |
* Adds zero or more index nodes for the given key and node. |
858 |
* Shared by plain and Cmp versions of put |
859 |
*/ |
860 |
private void addIndex(K key, Node<K,V> z) { |
861 |
if (key == null || z == null) // don't postpone errors |
862 |
throw new NullPointerException(); |
863 |
int rnd; // generate a random level |
864 |
Thread thread = Thread.currentThread(); |
865 |
if ((rnd = UNSAFE.getInt(thread, SECONDARY)) == 0) // initialize |
866 |
rnd = ThreadLocalRandom.current().nextInt(); |
867 |
rnd ^= rnd << 13; // xorshift |
868 |
rnd ^= rnd >>> 17; |
869 |
rnd ^= rnd << 5; |
870 |
UNSAFE.putInt(thread, SECONDARY, rnd); |
871 |
if ((rnd & 0x80000001) == 0) { // test highest and lowest bits |
872 |
int level = 1, max; |
873 |
while (((rnd >>>= 1) & 1) != 0) |
874 |
++level; |
875 |
Index<K,V> idx = null; |
876 |
HeadIndex<K,V> h = head; |
877 |
if (level <= (max = h.level)) { |
878 |
for (int i = 1; i <= level; ++i) |
879 |
idx = new Index<K,V>(z, idx, null); |
880 |
} |
881 |
else { // try to grow by one level |
882 |
level = max + 1; // hold in array and later pick the one to use |
883 |
Index<K,V>[] idxs = (Index<K,V>[])new Index<?,?>[level+1]; |
884 |
for (int i = 1; i <= level; ++i) |
885 |
idxs[i] = idx = new Index<K,V>(z, idx, null); |
886 |
for (;;) { |
887 |
h = head; |
888 |
int oldLevel = h.level; |
889 |
if (level <= oldLevel) // lost race to add level |
890 |
break; |
891 |
HeadIndex<K,V> newh = h; |
892 |
Node<K,V> oldbase = h.node; |
893 |
for (int j = oldLevel+1; j <= level; ++j) |
894 |
newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j); |
895 |
if (casHead(h, newh)) { |
896 |
h = newh; |
897 |
idx = idxs[level = oldLevel]; |
898 |
break; |
899 |
} |
900 |
} |
901 |
} |
902 |
Comparator<? super K> cmp = comparator; |
903 |
for (int insertionLevel = level;;) { // find insertion points; splice |
904 |
int j = h.level; |
905 |
Index<K,V> q = h; |
906 |
Index<K,V> r = q.right; |
907 |
Index<K,V> t = idx; |
908 |
for (;;) { |
909 |
if (q == null || t == null) |
910 |
return; |
911 |
if (r != null) { |
912 |
Node<K,V> n = r.node; |
913 |
// compare before deletion check avoids needing recheck |
914 |
int c = (cmp == null) ? |
915 |
((Comparable<? super K>)key).compareTo(n.key) : |
916 |
cmp.compare(key, n.key); |
917 |
if (n.value == null) { |
918 |
if (!q.unlink(r)) |
919 |
break; |
920 |
r = q.right; |
921 |
continue; |
922 |
} |
923 |
if (c > 0) { |
924 |
q = r; |
925 |
r = r.right; |
926 |
continue; |
927 |
} |
928 |
} |
929 |
|
930 |
if (j == insertionLevel) { |
931 |
if (!q.link(r, t)) |
932 |
break; // restart |
933 |
if (t.node.value == null) { |
934 |
if (cmp == null) // node deleted; clean up |
935 |
findNode((Comparable<? super K>)key); |
936 |
else |
937 |
findNodeCmp(cmp, key); |
938 |
return; |
939 |
} |
940 |
if (--insertionLevel == 0) |
941 |
return; |
942 |
} |
943 |
|
944 |
if (--j >= insertionLevel && j < level) |
945 |
t = t.down; |
946 |
q = q.down; |
947 |
r = q.right; |
948 |
} |
949 |
} |
950 |
} |
951 |
} |
952 |
|
953 |
/* ---------------- Deletion -------------- */ |
954 |
|
955 |
/** |
956 |
* Main deletion method. Locates node, nulls value, appends a |
957 |
* deletion marker, unlinks predecessor, removes associated index |
958 |
* nodes, and possibly reduces head index level. |
959 |
* |
960 |
* Index nodes are cleared out simply by calling findPredecessor. |
961 |
* which unlinks indexes to deleted nodes found along path to key, |
962 |
* which will include the indexes to this node. This is done |
963 |
* unconditionally. We can't check beforehand whether there are |
964 |
* index nodes because it might be the case that some or all |
965 |
* indexes hadn't been inserted yet for this node during initial |
966 |
* search for it, and we'd like to ensure lack of garbage |
967 |
* retention, so must call to be sure. |
968 |
* |
969 |
* @param okey the key |
970 |
* @param value if non-null, the value that must be |
971 |
* associated with key |
972 |
* @return the node, or null if not found |
973 |
*/ |
974 |
final V doRemove(Object okey, Object value) { |
975 |
if (okey == null) |
976 |
throw new NullPointerException(); |
977 |
@SuppressWarnings("unchecked") Comparable<? super K> key = |
978 |
(Comparable<? super K>)okey; |
979 |
for (;;) { |
980 |
Node<K,V> b = findPredecessor(key); |
981 |
Node<K,V> n = b.next; |
982 |
for (;;) { |
983 |
if (n == null) |
984 |
return null; |
985 |
Node<K,V> f = n.next; |
986 |
if (n != b.next) // inconsistent read |
987 |
break; |
988 |
Object v = n.value; |
989 |
if (v == null) { // n is deleted |
990 |
n.helpDelete(b, f); |
991 |
break; |
992 |
} |
993 |
if (v == n || b.value == null) // b is deleted |
994 |
break; |
995 |
int c = key.compareTo(n.key); |
996 |
if (c < 0) |
997 |
return null; |
998 |
if (c > 0) { |
999 |
b = n; |
1000 |
n = f; |
1001 |
continue; |
1002 |
} |
1003 |
if (value != null && !value.equals(v)) |
1004 |
return null; |
1005 |
if (!n.casValue(v, null)) |
1006 |
break; |
1007 |
if (!n.appendMarker(f) || !b.casNext(n, f)) |
1008 |
findNode(key); // Retry via findNode |
1009 |
else { |
1010 |
findPredecessor(key); // Clean index |
1011 |
if (head.right == null) |
1012 |
tryReduceLevel(); |
1013 |
} |
1014 |
return (V)v; |
1015 |
} |
1016 |
} |
1017 |
} |
1018 |
|
1019 |
/** |
1020 |
* Possibly reduce head level if it has no nodes. This method can |
1021 |
* (rarely) make mistakes, in which case levels can disappear even |
1022 |
* though they are about to contain index nodes. This impacts |
1023 |
* performance, not correctness. To minimize mistakes as well as |
1024 |
* to reduce hysteresis, the level is reduced by one only if the |
1025 |
* topmost three levels look empty. Also, if the removed level |
1026 |
* looks non-empty after CAS, we try to change it back quick |
1027 |
* before anyone notices our mistake! (This trick works pretty |
1028 |
* well because this method will practically never make mistakes |
1029 |
* unless current thread stalls immediately before first CAS, in |
1030 |
* which case it is very unlikely to stall again immediately |
1031 |
* afterwards, so will recover.) |
1032 |
* |
1033 |
* We put up with all this rather than just let levels grow |
1034 |
* because otherwise, even a small map that has undergone a large |
1035 |
* number of insertions and removals will have a lot of levels, |
1036 |
* slowing down access more than would an occasional unwanted |
1037 |
* reduction. |
1038 |
*/ |
1039 |
private void tryReduceLevel() { |
1040 |
HeadIndex<K,V> h = head; |
1041 |
HeadIndex<K,V> d; |
1042 |
HeadIndex<K,V> e; |
1043 |
if (h.level > 3 && |
1044 |
(d = (HeadIndex<K,V>)h.down) != null && |
1045 |
(e = (HeadIndex<K,V>)d.down) != null && |
1046 |
e.right == null && |
1047 |
d.right == null && |
1048 |
h.right == null && |
1049 |
casHead(h, d) && // try to set |
1050 |
h.right != null) // recheck |
1051 |
casHead(d, h); // try to backout |
1052 |
} |
1053 |
|
1054 |
/* ---------------- Finding and removing first element -------------- */ |
1055 |
|
1056 |
/** |
1057 |
* Specialized variant of findNode to get first valid node. |
1058 |
* @return first node or null if empty |
1059 |
*/ |
1060 |
Node<K,V> findFirst() { |
1061 |
for (;;) { |
1062 |
Node<K,V> b = head.node; |
1063 |
Node<K,V> n = b.next; |
1064 |
if (n == null) |
1065 |
return null; |
1066 |
if (n.value != null) |
1067 |
return n; |
1068 |
n.helpDelete(b, n.next); |
1069 |
} |
1070 |
} |
1071 |
|
1072 |
/** |
1073 |
* Removes first entry; returns its snapshot. |
1074 |
* @return null if empty, else snapshot of first entry |
1075 |
*/ |
1076 |
Map.Entry<K,V> doRemoveFirstEntry() { |
1077 |
for (;;) { |
1078 |
Node<K,V> b = head.node; |
1079 |
Node<K,V> n = b.next; |
1080 |
if (n == null) |
1081 |
return null; |
1082 |
Node<K,V> f = n.next; |
1083 |
if (n != b.next) |
1084 |
continue; |
1085 |
Object v = n.value; |
1086 |
if (v == null) { |
1087 |
n.helpDelete(b, f); |
1088 |
continue; |
1089 |
} |
1090 |
if (!n.casValue(v, null)) |
1091 |
continue; |
1092 |
if (!n.appendMarker(f) || !b.casNext(n, f)) |
1093 |
findFirst(); // retry |
1094 |
clearIndexToFirst(); |
1095 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v); |
1096 |
} |
1097 |
} |
1098 |
|
1099 |
/** |
1100 |
* Clears out index nodes associated with deleted first entry. |
1101 |
*/ |
1102 |
private void clearIndexToFirst() { |
1103 |
for (;;) { |
1104 |
Index<K,V> q = head; |
1105 |
for (;;) { |
1106 |
Index<K,V> r = q.right; |
1107 |
if (r != null && r.indexesDeletedNode() && !q.unlink(r)) |
1108 |
break; |
1109 |
if ((q = q.down) == null) { |
1110 |
if (head.right == null) |
1111 |
tryReduceLevel(); |
1112 |
return; |
1113 |
} |
1114 |
} |
1115 |
} |
1116 |
} |
1117 |
|
1118 |
/** |
1119 |
* Removes last entry; returns its snapshot. |
1120 |
* Specialized variant of doRemove. |
1121 |
* @return null if empty, else snapshot of last entry |
1122 |
*/ |
1123 |
Map.Entry<K,V> doRemoveLastEntry() { |
1124 |
for (;;) { |
1125 |
Node<K,V> b = findPredecessorOfLast(); |
1126 |
Node<K,V> n = b.next; |
1127 |
if (n == null) { |
1128 |
if (b.isBaseHeader()) // empty |
1129 |
return null; |
1130 |
else |
1131 |
continue; // all b's successors are deleted; retry |
1132 |
} |
1133 |
for (;;) { |
1134 |
Node<K,V> f = n.next; |
1135 |
if (n != b.next) // inconsistent read |
1136 |
break; |
1137 |
Object v = n.value; |
1138 |
if (v == null) { // n is deleted |
1139 |
n.helpDelete(b, f); |
1140 |
break; |
1141 |
} |
1142 |
if (v == n || b.value == null) // b is deleted |
1143 |
break; |
1144 |
if (f != null) { |
1145 |
b = n; |
1146 |
n = f; |
1147 |
continue; |
1148 |
} |
1149 |
if (!n.casValue(v, null)) |
1150 |
break; |
1151 |
K key = n.key; |
1152 |
Comparator<? super K> cmp = comparator; |
1153 |
if (!n.appendMarker(f) || !b.casNext(n, f)) { |
1154 |
if (cmp == null) // Retry via findNode |
1155 |
findNode((Comparable<? super K>)key); |
1156 |
else |
1157 |
findNodeCmp(cmp, key); |
1158 |
} |
1159 |
else { // Clean index |
1160 |
if (cmp == null) |
1161 |
findPredecessor((Comparable<? super K>)key); |
1162 |
else |
1163 |
findPredecessorCmp(cmp, key); |
1164 |
if (head.right == null) |
1165 |
tryReduceLevel(); |
1166 |
} |
1167 |
return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v); |
1168 |
} |
1169 |
} |
1170 |
} |
1171 |
|
1172 |
/* ---------------- Finding and removing last element -------------- */ |
1173 |
|
1174 |
/** |
1175 |
* Specialized version of find to get last valid node. |
1176 |
* @return last node or null if empty |
1177 |
*/ |
1178 |
Node<K,V> findLast() { |
1179 |
/* |
1180 |
* findPredecessor can't be used to traverse index level |
1181 |
* because this doesn't use comparisons. So traversals of |
1182 |
* both levels are folded together. |
1183 |
*/ |
1184 |
Index<K,V> q = head; |
1185 |
for (;;) { |
1186 |
Index<K,V> d, r; |
1187 |
if ((r = q.right) != null) { |
1188 |
if (r.indexesDeletedNode()) { |
1189 |
q.unlink(r); |
1190 |
q = head; // restart |
1191 |
} |
1192 |
else |
1193 |
q = r; |
1194 |
} else if ((d = q.down) != null) { |
1195 |
q = d; |
1196 |
} else { |
1197 |
Node<K,V> b = q.node; |
1198 |
Node<K,V> n = b.next; |
1199 |
for (;;) { |
1200 |
if (n == null) |
1201 |
return b.isBaseHeader() ? null : b; |
1202 |
Node<K,V> f = n.next; // inconsistent read |
1203 |
if (n != b.next) |
1204 |
break; |
1205 |
Object v = n.value; |
1206 |
if (v == null) { // n is deleted |
1207 |
n.helpDelete(b, f); |
1208 |
break; |
1209 |
} |
1210 |
if (v == n || b.value == null) // b is deleted |
1211 |
break; |
1212 |
b = n; |
1213 |
n = f; |
1214 |
} |
1215 |
q = head; // restart |
1216 |
} |
1217 |
} |
1218 |
} |
1219 |
|
1220 |
/** |
1221 |
* Specialized variant of findPredecessor to get predecessor of last |
1222 |
* valid node. Needed when removing the last entry. It is possible |
1223 |
* that all successors of returned node will have been deleted upon |
1224 |
* return, in which case this method can be retried. |
1225 |
* @return likely predecessor of last node |
1226 |
*/ |
1227 |
private Node<K,V> findPredecessorOfLast() { |
1228 |
for (;;) { |
1229 |
Index<K,V> q = head; |
1230 |
for (;;) { |
1231 |
Index<K,V> d, r; |
1232 |
if ((r = q.right) != null) { |
1233 |
if (r.indexesDeletedNode()) { |
1234 |
q.unlink(r); |
1235 |
break; // must restart |
1236 |
} |
1237 |
// proceed as far across as possible without overshooting |
1238 |
if (r.node.next != null) { |
1239 |
q = r; |
1240 |
continue; |
1241 |
} |
1242 |
} |
1243 |
if ((d = q.down) != null) |
1244 |
q = d; |
1245 |
else |
1246 |
return q.node; |
1247 |
} |
1248 |
} |
1249 |
} |
1250 |
|
1251 |
/* ---------------- Relational operations -------------- */ |
1252 |
|
1253 |
// Control values OR'ed as arguments to findNear |
1254 |
|
1255 |
private static final int EQ = 1; |
1256 |
private static final int LT = 2; |
1257 |
private static final int GT = 0; // Actually checked as !LT |
1258 |
|
1259 |
/** |
1260 |
* Utility for ceiling, floor, lower, higher methods. |
1261 |
* @param kkey the key |
1262 |
* @param rel the relation -- OR'ed combination of EQ, LT, GT |
1263 |
* @return nearest node fitting relation, or null if no such |
1264 |
*/ |
1265 |
Node<K,V> doFindNear(K kkey, int rel) { |
1266 |
@SuppressWarnings("unchecked") Comparable<? super K> key = |
1267 |
(Comparable<? super K>)kkey; |
1268 |
for (;;) { |
1269 |
Node<K,V> b = findPredecessor(key); |
1270 |
Node<K,V> n = b.next; |
1271 |
for (;;) { |
1272 |
if (n == null) |
1273 |
return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b; |
1274 |
Node<K,V> f = n.next; |
1275 |
if (n != b.next) // inconsistent read |
1276 |
break; |
1277 |
Object v = n.value; |
1278 |
if (v == null) { // n is deleted |
1279 |
n.helpDelete(b, f); |
1280 |
break; |
1281 |
} |
1282 |
if (v == n || b.value == null) // b is deleted |
1283 |
break; |
1284 |
int c = key.compareTo(n.key); |
1285 |
if ((c == 0 && (rel & EQ) != 0) || |
1286 |
(c < 0 && (rel & LT) == 0)) |
1287 |
return n; |
1288 |
if ( c <= 0 && (rel & LT) != 0) |
1289 |
return b.isBaseHeader() ? null : b; |
1290 |
b = n; |
1291 |
n = f; |
1292 |
} |
1293 |
} |
1294 |
} |
1295 |
|
1296 |
/* ---------------- cmp versions -------------- */ |
1297 |
|
1298 |
// Boringly almost the same as natural-Comparable ones |
1299 |
|
1300 |
private Node<K,V> findPredecessorCmp(Comparator<? super K> cmp, Object okey) { |
1301 |
if (cmp == null) |
1302 |
throw new NullPointerException(); // don't postpone errors |
1303 |
@SuppressWarnings("unchecked") K key = (K) okey; |
1304 |
for (;;) { |
1305 |
Index<K,V> q = head; |
1306 |
Index<K,V> r = q.right; |
1307 |
for (;;) { |
1308 |
if (r != null) { |
1309 |
Node<K,V> n = r.node; |
1310 |
K k = n.key; |
1311 |
if (n.value == null) { |
1312 |
if (!q.unlink(r)) |
1313 |
break; // restart |
1314 |
r = q.right; // reread r |
1315 |
continue; |
1316 |
} |
1317 |
if (cmp.compare(key, k) > 0) { |
1318 |
q = r; |
1319 |
r = r.right; |
1320 |
continue; |
1321 |
} |
1322 |
} |
1323 |
Index<K,V> d = q.down; |
1324 |
if (d != null) { |
1325 |
q = d; |
1326 |
r = d.right; |
1327 |
} else |
1328 |
return q.node; |
1329 |
} |
1330 |
} |
1331 |
} |
1332 |
|
1333 |
private Node<K,V> findNodeCmp(Comparator<? super K> cmp, Object okey) { |
1334 |
if (cmp == null) |
1335 |
throw new NullPointerException(); // don't postpone errors |
1336 |
@SuppressWarnings("unchecked") K key = (K) okey; |
1337 |
for (;;) { |
1338 |
Node<K,V> b = findPredecessorCmp(cmp, key); |
1339 |
Node<K,V> n = b.next; |
1340 |
for (;;) { |
1341 |
if (n == null) |
1342 |
return null; |
1343 |
Node<K,V> f = n.next; |
1344 |
if (n != b.next) // inconsistent read |
1345 |
break; |
1346 |
Object v = n.value; |
1347 |
if (v == null) { // n is deleted |
1348 |
n.helpDelete(b, f); |
1349 |
break; |
1350 |
} |
1351 |
if (v == n || b.value == null) // b is deleted |
1352 |
break; |
1353 |
int c = cmp.compare(key, n.key); |
1354 |
if (c == 0) |
1355 |
return n; |
1356 |
if (c < 0) |
1357 |
return null; |
1358 |
b = n; |
1359 |
n = f; |
1360 |
} |
1361 |
} |
1362 |
} |
1363 |
|
1364 |
private V doGetCmp(Comparator<? super K> cmp, Object okey) { |
1365 |
if (cmp == null) |
1366 |
throw new NullPointerException(); // don't postpone errors |
1367 |
@SuppressWarnings("unchecked") K key = (K) okey; |
1368 |
for (;;) { |
1369 |
Node<K,V> b = findPredecessorCmp(cmp, key); |
1370 |
Node<K,V> n = b.next; |
1371 |
for (;;) { |
1372 |
if (n == null) |
1373 |
return null; |
1374 |
Node<K,V> f = n.next; |
1375 |
if (n != b.next) // inconsistent read |
1376 |
break; |
1377 |
Object v = n.value; |
1378 |
if (v == null) { // n is deleted |
1379 |
n.helpDelete(b, f); |
1380 |
break; |
1381 |
} |
1382 |
if (v == n || b.value == null) // b is deleted |
1383 |
break; |
1384 |
int c = cmp.compare(key, n.key); |
1385 |
if (c == 0) |
1386 |
return (V)v; |
1387 |
if (c < 0) |
1388 |
return null; |
1389 |
b = n; |
1390 |
n = f; |
1391 |
} |
1392 |
} |
1393 |
} |
1394 |
|
1395 |
private V doPutCmp(Comparator<? super K> cmp, K key, V value, boolean onlyIfAbsent) { |
1396 |
if (cmp == null) |
1397 |
throw new NullPointerException(); // don't postpone errors |
1398 |
for (;;) { |
1399 |
Node<K,V> b = findPredecessorCmp(cmp, key); |
1400 |
Node<K,V> n = b.next; |
1401 |
for (;;) { |
1402 |
if (n != null) { |
1403 |
Node<K,V> f = n.next; |
1404 |
if (n != b.next) // inconsistent read |
1405 |
break; |
1406 |
Object v = n.value; |
1407 |
if (v == null) { // n is deleted |
1408 |
n.helpDelete(b, f); |
1409 |
break; |
1410 |
} |
1411 |
if (v == n || b.value == null) // b is deleted |
1412 |
break; |
1413 |
int c = cmp.compare(key, n.key); |
1414 |
if (c > 0) { |
1415 |
b = n; |
1416 |
n = f; |
1417 |
continue; |
1418 |
} |
1419 |
if (c == 0) { |
1420 |
if (onlyIfAbsent || n.casValue(v, value)) |
1421 |
return (V)v; |
1422 |
else |
1423 |
break; // restart if lost race to replace value |
1424 |
} |
1425 |
// else c < 0; fall through |
1426 |
} |
1427 |
|
1428 |
Node<K,V> z = new Node<K,V>(key, value, n); |
1429 |
if (!b.casNext(n, z)) |
1430 |
break; // restart if lost race to append to b |
1431 |
addIndex(key, z); |
1432 |
return null; |
1433 |
} |
1434 |
} |
1435 |
} |
1436 |
|
1437 |
final V doRemoveCmp(Comparator<? super K> cmp, Object okey, Object value) { |
1438 |
if (cmp == null) |
1439 |
throw new NullPointerException(); // don't postpone errors |
1440 |
@SuppressWarnings("unchecked") K key = (K) okey; |
1441 |
for (;;) { |
1442 |
Node<K,V> b = findPredecessorCmp(cmp, key); |
1443 |
Node<K,V> n = b.next; |
1444 |
for (;;) { |
1445 |
if (n == null) |
1446 |
return null; |
1447 |
Node<K,V> f = n.next; |
1448 |
if (n != b.next) // inconsistent read |
1449 |
break; |
1450 |
Object v = n.value; |
1451 |
if (v == null) { // n is deleted |
1452 |
n.helpDelete(b, f); |
1453 |
break; |
1454 |
} |
1455 |
if (v == n || b.value == null) // b is deleted |
1456 |
break; |
1457 |
int c = cmp.compare(key, n.key); |
1458 |
if (c < 0) |
1459 |
return null; |
1460 |
if (c > 0) { |
1461 |
b = n; |
1462 |
n = f; |
1463 |
continue; |
1464 |
} |
1465 |
if (value != null && !value.equals(v)) |
1466 |
return null; |
1467 |
if (!n.casValue(v, null)) |
1468 |
break; |
1469 |
if (!n.appendMarker(f) || !b.casNext(n, f)) |
1470 |
findNodeCmp(cmp, key); // Retry via findNode |
1471 |
else { |
1472 |
findPredecessorCmp(cmp, key); // Clean index |
1473 |
if (head.right == null) |
1474 |
tryReduceLevel(); |
1475 |
} |
1476 |
return (V)v; |
1477 |
} |
1478 |
} |
1479 |
} |
1480 |
|
1481 |
Node<K,V> doFindNearCmp(Comparator<? super K> cmp, K key, int rel) { |
1482 |
if (cmp == null) |
1483 |
throw new NullPointerException(); // don't postpone errors |
1484 |
for (;;) { |
1485 |
Node<K,V> b = findPredecessorCmp(cmp, key); |
1486 |
Node<K,V> n = b.next; |
1487 |
for (;;) { |
1488 |
if (n == null) |
1489 |
return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b; |
1490 |
Node<K,V> f = n.next; |
1491 |
if (n != b.next) // inconsistent read |
1492 |
break; |
1493 |
Object v = n.value; |
1494 |
if (v == null) { // n is deleted |
1495 |
n.helpDelete(b, f); |
1496 |
break; |
1497 |
} |
1498 |
if (v == n || b.value == null) // b is deleted |
1499 |
break; |
1500 |
int c = cmp.compare(key, n.key); |
1501 |
if ((c == 0 && (rel & EQ) != 0) || |
1502 |
(c < 0 && (rel & LT) == 0)) |
1503 |
return n; |
1504 |
if ( c <= 0 && (rel & LT) != 0) |
1505 |
return b.isBaseHeader() ? null : b; |
1506 |
b = n; |
1507 |
n = f; |
1508 |
} |
1509 |
} |
1510 |
} |
1511 |
|
1512 |
/* ---------------- Relays to natural vs cmp methods -------------- */ |
1513 |
|
1514 |
Node<K,V> findNear(K key, int rel) { |
1515 |
Comparator<? super K> cmp; |
1516 |
return (cmp = comparator) == null ? doFindNear(key, rel) : |
1517 |
doFindNearCmp(cmp, key, rel); |
1518 |
} |
1519 |
|
1520 |
/** |
1521 |
* Returns SimpleImmutableEntry for results of findNear. |
1522 |
* @param key the key |
1523 |
* @param rel the relation -- OR'ed combination of EQ, LT, GT |
1524 |
* @return Entry fitting relation, or null if no such |
1525 |
*/ |
1526 |
AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) { |
1527 |
for (;;) { |
1528 |
Node<K,V> n = findNear(key, rel); |
1529 |
if (n == null) |
1530 |
return null; |
1531 |
AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); |
1532 |
if (e != null) |
1533 |
return e; |
1534 |
} |
1535 |
} |
1536 |
|
1537 |
/* ---------------- Constructors -------------- */ |
1538 |
|
1539 |
/** |
1540 |
* Constructs a new, empty map, sorted according to the |
1541 |
* {@linkplain Comparable natural ordering} of the keys. |
1542 |
*/ |
1543 |
public ConcurrentSkipListMap() { |
1544 |
this.comparator = null; |
1545 |
initialize(); |
1546 |
} |
1547 |
|
1548 |
/** |
1549 |
* Constructs a new, empty map, sorted according to the specified |
1550 |
* comparator. |
1551 |
* |
1552 |
* @param comparator the comparator that will be used to order this map. |
1553 |
* If {@code null}, the {@linkplain Comparable natural |
1554 |
* ordering} of the keys will be used. |
1555 |
*/ |
1556 |
public ConcurrentSkipListMap(Comparator<? super K> comparator) { |
1557 |
this.comparator = comparator; |
1558 |
initialize(); |
1559 |
} |
1560 |
|
1561 |
/** |
1562 |
* Constructs a new map containing the same mappings as the given map, |
1563 |
* sorted according to the {@linkplain Comparable natural ordering} of |
1564 |
* the keys. |
1565 |
* |
1566 |
* @param m the map whose mappings are to be placed in this map |
1567 |
* @throws ClassCastException if the keys in {@code m} are not |
1568 |
* {@link Comparable}, or are not mutually comparable |
1569 |
* @throws NullPointerException if the specified map or any of its keys |
1570 |
* or values are null |
1571 |
*/ |
1572 |
public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) { |
1573 |
this.comparator = null; |
1574 |
initialize(); |
1575 |
putAll(m); |
1576 |
} |
1577 |
|
1578 |
/** |
1579 |
* Constructs a new map containing the same mappings and using the |
1580 |
* same ordering as the specified sorted map. |
1581 |
* |
1582 |
* @param m the sorted map whose mappings are to be placed in this |
1583 |
* map, and whose comparator is to be used to sort this map |
1584 |
* @throws NullPointerException if the specified sorted map or any of |
1585 |
* its keys or values are null |
1586 |
*/ |
1587 |
public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) { |
1588 |
this.comparator = m.comparator(); |
1589 |
initialize(); |
1590 |
buildFromSorted(m); |
1591 |
} |
1592 |
|
1593 |
/** |
1594 |
* Creates a new {@link Set} backed by a ConcurrentSkipListMap |
1595 |
* from the given type to {@code Boolean.TRUE}. |
1596 |
* |
1597 |
* @return the new set |
1598 |
*/ |
1599 |
public static <K> KeySetView<K,Boolean> newKeySet() { |
1600 |
return new KeySetView<K,Boolean>(new ConcurrentSkipListMap<K,Boolean>(), |
1601 |
Boolean.TRUE); |
1602 |
} |
1603 |
|
1604 |
/** |
1605 |
* Creates a new {@link Set} backed by a ConcurrentSkipListMap |
1606 |
* from the given type to {@code Boolean.TRUE}, using the |
1607 |
* given comparator. |
1608 |
* |
1609 |
* @param comparator the comparator that will be used to order this map. |
1610 |
* If {@code null}, the {@linkplain Comparable natural |
1611 |
* ordering} of the keys will be used. |
1612 |
* |
1613 |
* @return the new set |
1614 |
*/ |
1615 |
public static <K> KeySetView<K,Boolean> newKeySet(Comparator<? super K> comparator) { |
1616 |
return new KeySetView<K,Boolean> |
1617 |
(new ConcurrentSkipListMap<K,Boolean>(comparator), Boolean.TRUE); |
1618 |
} |
1619 |
|
1620 |
/** |
1621 |
* Returns a shallow copy of this {@code ConcurrentSkipListMap} |
1622 |
* instance. (The keys and values themselves are not cloned.) |
1623 |
* |
1624 |
* @return a shallow copy of this map |
1625 |
*/ |
1626 |
public ConcurrentSkipListMap<K,V> clone() { |
1627 |
try { |
1628 |
@SuppressWarnings("unchecked") |
1629 |
ConcurrentSkipListMap<K,V> clone = |
1630 |
(ConcurrentSkipListMap<K,V>) super.clone(); |
1631 |
clone.initialize(); |
1632 |
clone.buildFromSorted(this); |
1633 |
return clone; |
1634 |
} catch (CloneNotSupportedException e) { |
1635 |
throw new InternalError(); |
1636 |
} |
1637 |
} |
1638 |
|
1639 |
/** |
1640 |
* Streamlined bulk insertion to initialize from elements of |
1641 |
* given sorted map. Call only from constructor or clone |
1642 |
* method. |
1643 |
*/ |
1644 |
private void buildFromSorted(SortedMap<K, ? extends V> map) { |
1645 |
if (map == null) |
1646 |
throw new NullPointerException(); |
1647 |
|
1648 |
HeadIndex<K,V> h = head; |
1649 |
Node<K,V> basepred = h.node; |
1650 |
|
1651 |
// Track the current rightmost node at each level. Uses an |
1652 |
// ArrayList to avoid committing to initial or maximum level. |
1653 |
ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>(); |
1654 |
|
1655 |
// initialize |
1656 |
for (int i = 0; i <= h.level; ++i) |
1657 |
preds.add(null); |
1658 |
Index<K,V> q = h; |
1659 |
for (int i = h.level; i > 0; --i) { |
1660 |
preds.set(i, q); |
1661 |
q = q.down; |
1662 |
} |
1663 |
|
1664 |
Iterator<? extends Map.Entry<? extends K, ? extends V>> it = |
1665 |
map.entrySet().iterator(); |
1666 |
while (it.hasNext()) { |
1667 |
Map.Entry<? extends K, ? extends V> e = it.next(); |
1668 |
int rnd = ThreadLocalRandom.current().nextInt(); |
1669 |
int j = 0; |
1670 |
if ((rnd & 0x80000001) == 0) { |
1671 |
do { |
1672 |
++j; |
1673 |
} while (((rnd >>>= 1) & 1) != 0); |
1674 |
if (j > h.level) j = h.level + 1; |
1675 |
} |
1676 |
K k = e.getKey(); |
1677 |
V v = e.getValue(); |
1678 |
if (k == null || v == null) |
1679 |
throw new NullPointerException(); |
1680 |
Node<K,V> z = new Node<K,V>(k, v, null); |
1681 |
basepred.next = z; |
1682 |
basepred = z; |
1683 |
if (j > 0) { |
1684 |
Index<K,V> idx = null; |
1685 |
for (int i = 1; i <= j; ++i) { |
1686 |
idx = new Index<K,V>(z, idx, null); |
1687 |
if (i > h.level) |
1688 |
h = new HeadIndex<K,V>(h.node, h, idx, i); |
1689 |
|
1690 |
if (i < preds.size()) { |
1691 |
preds.get(i).right = idx; |
1692 |
preds.set(i, idx); |
1693 |
} else |
1694 |
preds.add(idx); |
1695 |
} |
1696 |
} |
1697 |
} |
1698 |
head = h; |
1699 |
} |
1700 |
|
1701 |
/* ---------------- Serialization -------------- */ |
1702 |
|
1703 |
/** |
1704 |
* Saves this map to a stream (that is, serializes it). |
1705 |
* |
1706 |
* @serialData The key (Object) and value (Object) for each |
1707 |
* key-value mapping represented by the map, followed by |
1708 |
* {@code null}. The key-value mappings are emitted in key-order |
1709 |
* (as determined by the Comparator, or by the keys' natural |
1710 |
* ordering if no Comparator). |
1711 |
*/ |
1712 |
private void writeObject(java.io.ObjectOutputStream s) |
1713 |
throws java.io.IOException { |
1714 |
// Write out the Comparator and any hidden stuff |
1715 |
s.defaultWriteObject(); |
1716 |
|
1717 |
// Write out keys and values (alternating) |
1718 |
for (Node<K,V> n = findFirst(); n != null; n = n.next) { |
1719 |
V v = n.getValidValue(); |
1720 |
if (v != null) { |
1721 |
s.writeObject(n.key); |
1722 |
s.writeObject(v); |
1723 |
} |
1724 |
} |
1725 |
s.writeObject(null); |
1726 |
} |
1727 |
|
1728 |
/** |
1729 |
* Reconstitutes this map from a stream (that is, deserializes it). |
1730 |
*/ |
1731 |
private void readObject(final java.io.ObjectInputStream s) |
1732 |
throws java.io.IOException, ClassNotFoundException { |
1733 |
// Read in the Comparator and any hidden stuff |
1734 |
s.defaultReadObject(); |
1735 |
// Reset transients |
1736 |
initialize(); |
1737 |
|
1738 |
/* |
1739 |
* This is nearly identical to buildFromSorted, but is |
1740 |
* distinct because readObject calls can't be nicely adapted |
1741 |
* as the kind of iterator needed by buildFromSorted. (They |
1742 |
* can be, but doing so requires type cheats and/or creation |
1743 |
* of adaptor classes.) It is simpler to just adapt the code. |
1744 |
*/ |
1745 |
|
1746 |
HeadIndex<K,V> h = head; |
1747 |
Node<K,V> basepred = h.node; |
1748 |
ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>(); |
1749 |
for (int i = 0; i <= h.level; ++i) |
1750 |
preds.add(null); |
1751 |
Index<K,V> q = h; |
1752 |
for (int i = h.level; i > 0; --i) { |
1753 |
preds.set(i, q); |
1754 |
q = q.down; |
1755 |
} |
1756 |
|
1757 |
for (;;) { |
1758 |
Object k = s.readObject(); |
1759 |
if (k == null) |
1760 |
break; |
1761 |
Object v = s.readObject(); |
1762 |
if (v == null) |
1763 |
throw new NullPointerException(); |
1764 |
K key = (K) k; |
1765 |
V val = (V) v; |
1766 |
int rnd = ThreadLocalRandom.current().nextInt(); |
1767 |
int j = 0; |
1768 |
if ((rnd & 0x80000001) == 0) { |
1769 |
do { |
1770 |
++j; |
1771 |
} while (((rnd >>>= 1) & 1) != 0); |
1772 |
if (j > h.level) j = h.level + 1; |
1773 |
} |
1774 |
Node<K,V> z = new Node<K,V>(key, val, null); |
1775 |
basepred.next = z; |
1776 |
basepred = z; |
1777 |
if (j > 0) { |
1778 |
Index<K,V> idx = null; |
1779 |
for (int i = 1; i <= j; ++i) { |
1780 |
idx = new Index<K,V>(z, idx, null); |
1781 |
if (i > h.level) |
1782 |
h = new HeadIndex<K,V>(h.node, h, idx, i); |
1783 |
|
1784 |
if (i < preds.size()) { |
1785 |
preds.get(i).right = idx; |
1786 |
preds.set(i, idx); |
1787 |
} else |
1788 |
preds.add(idx); |
1789 |
} |
1790 |
} |
1791 |
} |
1792 |
head = h; |
1793 |
} |
1794 |
|
1795 |
/* ------ Map API methods ------ */ |
1796 |
|
1797 |
/** |
1798 |
* Returns {@code true} if this map contains a mapping for the specified |
1799 |
* key. |
1800 |
* |
1801 |
* @param key key whose presence in this map is to be tested |
1802 |
* @return {@code true} if this map contains a mapping for the specified key |
1803 |
* @throws ClassCastException if the specified key cannot be compared |
1804 |
* with the keys currently in the map |
1805 |
* @throws NullPointerException if the specified key is null |
1806 |
*/ |
1807 |
public boolean containsKey(Object key) { |
1808 |
Comparator<? super K> cmp; |
1809 |
Object v = ((cmp = comparator) == null ? doGet(key) : |
1810 |
doGetCmp(cmp, key)); |
1811 |
return v != null; |
1812 |
} |
1813 |
|
1814 |
/** |
1815 |
* Returns the value to which the specified key is mapped, |
1816 |
* or {@code null} if this map contains no mapping for the key. |
1817 |
* |
1818 |
* <p>More formally, if this map contains a mapping from a key |
1819 |
* {@code k} to a value {@code v} such that {@code key} compares |
1820 |
* equal to {@code k} according to the map's ordering, then this |
1821 |
* method returns {@code v}; otherwise it returns {@code null}. |
1822 |
* (There can be at most one such mapping.) |
1823 |
* |
1824 |
* @throws ClassCastException if the specified key cannot be compared |
1825 |
* with the keys currently in the map |
1826 |
* @throws NullPointerException if the specified key is null |
1827 |
*/ |
1828 |
public V get(Object key) { |
1829 |
Comparator<? super K> cmp; |
1830 |
return ((cmp = comparator) == null) ? doGet(key) : doGetCmp(cmp, key); |
1831 |
} |
1832 |
|
1833 |
/** |
1834 |
* Associates the specified value with the specified key in this map. |
1835 |
* If the map previously contained a mapping for the key, the old |
1836 |
* value is replaced. |
1837 |
* |
1838 |
* @param key key with which the specified value is to be associated |
1839 |
* @param value value to be associated with the specified key |
1840 |
* @return the previous value associated with the specified key, or |
1841 |
* {@code null} if there was no mapping for the key |
1842 |
* @throws ClassCastException if the specified key cannot be compared |
1843 |
* with the keys currently in the map |
1844 |
* @throws NullPointerException if the specified key or value is null |
1845 |
*/ |
1846 |
public V put(K key, V value) { |
1847 |
Comparator<? super K> cmp; |
1848 |
if (value == null) |
1849 |
throw new NullPointerException(); |
1850 |
return ((cmp = comparator) == null) ? |
1851 |
doPut(key, value, false) : doPutCmp(cmp, key, value, false); |
1852 |
} |
1853 |
|
1854 |
/** |
1855 |
* Removes the mapping for the specified key from this map if present. |
1856 |
* |
1857 |
* @param key key for which mapping should be removed |
1858 |
* @return the previous value associated with the specified key, or |
1859 |
* {@code null} if there was no mapping for the key |
1860 |
* @throws ClassCastException if the specified key cannot be compared |
1861 |
* with the keys currently in the map |
1862 |
* @throws NullPointerException if the specified key is null |
1863 |
*/ |
1864 |
public V remove(Object key) { |
1865 |
Comparator<? super K> cmp; |
1866 |
return ((cmp = comparator) == null) ? doRemove(key, null) : |
1867 |
doRemoveCmp(cmp, key, null); |
1868 |
} |
1869 |
|
1870 |
/** |
1871 |
* Returns {@code true} if this map maps one or more keys to the |
1872 |
* specified value. This operation requires time linear in the |
1873 |
* map size. Additionally, it is possible for the map to change |
1874 |
* during execution of this method, in which case the returned |
1875 |
* result may be inaccurate. |
1876 |
* |
1877 |
* @param value value whose presence in this map is to be tested |
1878 |
* @return {@code true} if a mapping to {@code value} exists; |
1879 |
* {@code false} otherwise |
1880 |
* @throws NullPointerException if the specified value is null |
1881 |
*/ |
1882 |
public boolean containsValue(Object value) { |
1883 |
if (value == null) |
1884 |
throw new NullPointerException(); |
1885 |
for (Node<K,V> n = findFirst(); n != null; n = n.next) { |
1886 |
V v = n.getValidValue(); |
1887 |
if (v != null && value.equals(v)) |
1888 |
return true; |
1889 |
} |
1890 |
return false; |
1891 |
} |
1892 |
|
1893 |
/** |
1894 |
* Returns the number of key-value mappings in this map. If this map |
1895 |
* contains more than {@code Integer.MAX_VALUE} elements, it |
1896 |
* returns {@code Integer.MAX_VALUE}. |
1897 |
* |
1898 |
* <p>Beware that, unlike in most collections, this method is |
1899 |
* <em>NOT</em> a constant-time operation. Because of the |
1900 |
* asynchronous nature of these maps, determining the current |
1901 |
* number of elements requires traversing them all to count them. |
1902 |
* Additionally, it is possible for the size to change during |
1903 |
* execution of this method, in which case the returned result |
1904 |
* will be inaccurate. Thus, this method is typically not very |
1905 |
* useful in concurrent applications. |
1906 |
* |
1907 |
* @return the number of elements in this map |
1908 |
*/ |
1909 |
public int size() { |
1910 |
long count = 0; |
1911 |
for (Node<K,V> n = findFirst(); n != null; n = n.next) { |
1912 |
if (n.getValidValue() != null) |
1913 |
++count; |
1914 |
} |
1915 |
return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count; |
1916 |
} |
1917 |
|
1918 |
/** |
1919 |
* Returns {@code true} if this map contains no key-value mappings. |
1920 |
* @return {@code true} if this map contains no key-value mappings |
1921 |
*/ |
1922 |
public boolean isEmpty() { |
1923 |
return findFirst() == null; |
1924 |
} |
1925 |
|
1926 |
/** |
1927 |
* Removes all of the mappings from this map. |
1928 |
*/ |
1929 |
public void clear() { |
1930 |
initialize(); |
1931 |
} |
1932 |
|
1933 |
/* ---------------- View methods -------------- */ |
1934 |
|
1935 |
/* |
1936 |
* Note: Lazy initialization works for views because view classes |
1937 |
* are stateless/immutable so it doesn't matter wrt correctness if |
1938 |
* more than one is created (which will only rarely happen). Even |
1939 |
* so, the following idiom conservatively ensures that the method |
1940 |
* returns the one it created if it does so, not one created by |
1941 |
* another racing thread. |
1942 |
*/ |
1943 |
|
1944 |
/** |
1945 |
* Returns a {@link NavigableSet} view of the keys contained in this map. |
1946 |
* The set's iterator returns the keys in ascending order. |
1947 |
* The set is backed by the map, so changes to the map are |
1948 |
* reflected in the set, and vice-versa. The set supports element |
1949 |
* removal, which removes the corresponding mapping from the map, |
1950 |
* via the {@code Iterator.remove}, {@code Set.remove}, |
1951 |
* {@code removeAll}, {@code retainAll}, and {@code clear} |
1952 |
* operations. It does not support the {@code add} or {@code addAll} |
1953 |
* operations. |
1954 |
* |
1955 |
* <p>The view's {@code iterator} is a "weakly consistent" iterator |
1956 |
* that will never throw {@link ConcurrentModificationException}, |
1957 |
* and guarantees to traverse elements as they existed upon |
1958 |
* construction of the iterator, and may (but is not guaranteed to) |
1959 |
* reflect any modifications subsequent to construction. |
1960 |
* |
1961 |
* <p>This method is equivalent to method {@code navigableKeySet}. |
1962 |
* |
1963 |
* @return a navigable set view of the keys in this map |
1964 |
*/ |
1965 |
public NavigableSet<K> keySet() { |
1966 |
KeySetView<K,V> ks = keySet; |
1967 |
return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null)); |
1968 |
} |
1969 |
|
1970 |
public NavigableSet<K> navigableKeySet() { |
1971 |
KeySetView<K,V> ks = keySet; |
1972 |
return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null)); |
1973 |
} |
1974 |
|
1975 |
/** |
1976 |
* Returns a {@link Set} view of the keys in this map, using the |
1977 |
* given common mapped value for any additions (i.e., {@link |
1978 |
* Collection#add} and {@link Collection#addAll(Collection)}). |
1979 |
* This is of course only appropriate if it is acceptable to use |
1980 |
* the same value for all additions from this view. |
1981 |
* |
1982 |
* @param mappedValue the mapped value to use for any additions |
1983 |
* @return the set view |
1984 |
* @throws NullPointerException if the mappedValue is null |
1985 |
*/ |
1986 |
public KeySetView<K,V> keySet(V mappedValue) { |
1987 |
if (mappedValue == null) |
1988 |
throw new NullPointerException(); |
1989 |
return new KeySetView<K,V>(this, mappedValue); |
1990 |
} |
1991 |
|
1992 |
/** |
1993 |
* Returns a {@link Collection} view of the values contained in this map. |
1994 |
* The collection's iterator returns the values in ascending order |
1995 |
* of the corresponding keys. |
1996 |
* The collection is backed by the map, so changes to the map are |
1997 |
* reflected in the collection, and vice-versa. The collection |
1998 |
* supports element removal, which removes the corresponding |
1999 |
* mapping from the map, via the {@code Iterator.remove}, |
2000 |
* {@code Collection.remove}, {@code removeAll}, |
2001 |
* {@code retainAll} and {@code clear} operations. It does not |
2002 |
* support the {@code add} or {@code addAll} operations. |
2003 |
* |
2004 |
* <p>The view's {@code iterator} is a "weakly consistent" iterator |
2005 |
* that will never throw {@link ConcurrentModificationException}, |
2006 |
* and guarantees to traverse elements as they existed upon |
2007 |
* construction of the iterator, and may (but is not guaranteed to) |
2008 |
* reflect any modifications subsequent to construction. |
2009 |
*/ |
2010 |
public Collection<V> values() { |
2011 |
Values<V> vs = values; |
2012 |
return (vs != null) ? vs : (values = new Values<V>(this)); |
2013 |
} |
2014 |
|
2015 |
/** |
2016 |
* Returns a {@link Set} view of the mappings contained in this map. |
2017 |
* The set's iterator returns the entries in ascending key order. |
2018 |
* The set is backed by the map, so changes to the map are |
2019 |
* reflected in the set, and vice-versa. The set supports element |
2020 |
* removal, which removes the corresponding mapping from the map, |
2021 |
* via the {@code Iterator.remove}, {@code Set.remove}, |
2022 |
* {@code removeAll}, {@code retainAll} and {@code clear} |
2023 |
* operations. It does not support the {@code add} or |
2024 |
* {@code addAll} operations. |
2025 |
* |
2026 |
* <p>The view's {@code iterator} is a "weakly consistent" iterator |
2027 |
* that will never throw {@link ConcurrentModificationException}, |
2028 |
* and guarantees to traverse elements as they existed upon |
2029 |
* construction of the iterator, and may (but is not guaranteed to) |
2030 |
* reflect any modifications subsequent to construction. |
2031 |
* |
2032 |
* <p>The {@code Map.Entry} elements returned by |
2033 |
* {@code iterator.next()} do <em>not</em> support the |
2034 |
* {@code setValue} operation. |
2035 |
* |
2036 |
* @return a set view of the mappings contained in this map, |
2037 |
* sorted in ascending key order |
2038 |
*/ |
2039 |
public Set<Map.Entry<K,V>> entrySet() { |
2040 |
EntrySet<K,V> es = entrySet; |
2041 |
return (es != null) ? es : (entrySet = new EntrySet<K,V>(this)); |
2042 |
} |
2043 |
|
2044 |
public ConcurrentNavigableMap<K,V> descendingMap() { |
2045 |
ConcurrentNavigableMap<K,V> dm = descendingMap; |
2046 |
return (dm != null) ? dm : (descendingMap = new SubMap<K,V> |
2047 |
(this, null, false, null, false, true)); |
2048 |
} |
2049 |
|
2050 |
public NavigableSet<K> descendingKeySet() { |
2051 |
return descendingMap().navigableKeySet(); |
2052 |
} |
2053 |
|
2054 |
/* ---------------- AbstractMap Overrides -------------- */ |
2055 |
|
2056 |
/** |
2057 |
* Compares the specified object with this map for equality. |
2058 |
* Returns {@code true} if the given object is also a map and the |
2059 |
* two maps represent the same mappings. More formally, two maps |
2060 |
* {@code m1} and {@code m2} represent the same mappings if |
2061 |
* {@code m1.entrySet().equals(m2.entrySet())}. This |
2062 |
* operation may return misleading results if either map is |
2063 |
* concurrently modified during execution of this method. |
2064 |
* |
2065 |
* @param o object to be compared for equality with this map |
2066 |
* @return {@code true} if the specified object is equal to this map |
2067 |
*/ |
2068 |
public boolean equals(Object o) { |
2069 |
if (o == this) |
2070 |
return true; |
2071 |
if (!(o instanceof Map)) |
2072 |
return false; |
2073 |
Map<?,?> m = (Map<?,?>) o; |
2074 |
try { |
2075 |
for (Map.Entry<K,V> e : this.entrySet()) |
2076 |
if (! e.getValue().equals(m.get(e.getKey()))) |
2077 |
return false; |
2078 |
for (Map.Entry<?,?> e : m.entrySet()) { |
2079 |
Object k = e.getKey(); |
2080 |
Object v = e.getValue(); |
2081 |
if (k == null || v == null || !v.equals(get(k))) |
2082 |
return false; |
2083 |
} |
2084 |
return true; |
2085 |
} catch (ClassCastException unused) { |
2086 |
return false; |
2087 |
} catch (NullPointerException unused) { |
2088 |
return false; |
2089 |
} |
2090 |
} |
2091 |
|
2092 |
/* ------ ConcurrentMap API methods ------ */ |
2093 |
|
2094 |
/** |
2095 |
* {@inheritDoc} |
2096 |
* |
2097 |
* @return the previous value associated with the specified key, |
2098 |
* or {@code null} if there was no mapping for the key |
2099 |
* @throws ClassCastException if the specified key cannot be compared |
2100 |
* with the keys currently in the map |
2101 |
* @throws NullPointerException if the specified key or value is null |
2102 |
*/ |
2103 |
public V putIfAbsent(K key, V value) { |
2104 |
Comparator<? super K> cmp; |
2105 |
if (value == null) |
2106 |
throw new NullPointerException(); |
2107 |
return ((cmp = comparator) == null) ? |
2108 |
doPut(key, value, true) : doPutCmp(cmp, key, value, true); |
2109 |
} |
2110 |
|
2111 |
/** |
2112 |
* {@inheritDoc} |
2113 |
* |
2114 |
* @throws ClassCastException if the specified key cannot be compared |
2115 |
* with the keys currently in the map |
2116 |
* @throws NullPointerException if the specified key is null |
2117 |
*/ |
2118 |
public boolean remove(Object key, Object value) { |
2119 |
if (key == null) |
2120 |
throw new NullPointerException(); |
2121 |
if (value == null) |
2122 |
return false; |
2123 |
Comparator<? super K> cmp; |
2124 |
Object v = ((cmp = comparator) == null) ? doRemove(key, value) : |
2125 |
doRemoveCmp(cmp, key, value); |
2126 |
return v != null; |
2127 |
} |
2128 |
|
2129 |
/** |
2130 |
* {@inheritDoc} |
2131 |
* |
2132 |
* @throws ClassCastException if the specified key cannot be compared |
2133 |
* with the keys currently in the map |
2134 |
* @throws NullPointerException if any of the arguments are null |
2135 |
*/ |
2136 |
public boolean replace(K key, V oldValue, V newValue) { |
2137 |
if (oldValue == null || newValue == null) |
2138 |
throw new NullPointerException(); |
2139 |
Comparator<? super K> cmp = comparator; |
2140 |
for (;;) { |
2141 |
Node<K,V> n = (cmp == null) ? |
2142 |
findNode((Comparable<? super K>)key) : |
2143 |
findNodeCmp(cmp, key); |
2144 |
if (n == null) |
2145 |
return false; |
2146 |
Object v = n.value; |
2147 |
if (v != null) { |
2148 |
if (!oldValue.equals(v)) |
2149 |
return false; |
2150 |
if (n.casValue(v, newValue)) |
2151 |
return true; |
2152 |
} |
2153 |
} |
2154 |
} |
2155 |
|
2156 |
/** |
2157 |
* {@inheritDoc} |
2158 |
* |
2159 |
* @return the previous value associated with the specified key, |
2160 |
* or {@code null} if there was no mapping for the key |
2161 |
* @throws ClassCastException if the specified key cannot be compared |
2162 |
* with the keys currently in the map |
2163 |
* @throws NullPointerException if the specified key or value is null |
2164 |
*/ |
2165 |
public V replace(K key, V value) { |
2166 |
if (value == null) |
2167 |
throw new NullPointerException(); |
2168 |
Comparator<? super K> cmp = comparator; |
2169 |
for (;;) { |
2170 |
Node<K,V> n = (cmp == null) ? |
2171 |
findNode((Comparable<? super K>)key) : |
2172 |
findNodeCmp(cmp, key); |
2173 |
if (n == null) |
2174 |
return null; |
2175 |
Object v = n.value; |
2176 |
if (v != null && n.casValue(v, value)) |
2177 |
return (V)v; |
2178 |
} |
2179 |
} |
2180 |
|
2181 |
/* ------ SortedMap API methods ------ */ |
2182 |
|
2183 |
public Comparator<? super K> comparator() { |
2184 |
return comparator; |
2185 |
} |
2186 |
|
2187 |
/** |
2188 |
* @throws NoSuchElementException {@inheritDoc} |
2189 |
*/ |
2190 |
public K firstKey() { |
2191 |
Node<K,V> n = findFirst(); |
2192 |
if (n == null) |
2193 |
throw new NoSuchElementException(); |
2194 |
return n.key; |
2195 |
} |
2196 |
|
2197 |
/** |
2198 |
* @throws NoSuchElementException {@inheritDoc} |
2199 |
*/ |
2200 |
public K lastKey() { |
2201 |
Node<K,V> n = findLast(); |
2202 |
if (n == null) |
2203 |
throw new NoSuchElementException(); |
2204 |
return n.key; |
2205 |
} |
2206 |
|
2207 |
/** |
2208 |
* @throws ClassCastException {@inheritDoc} |
2209 |
* @throws NullPointerException if {@code fromKey} or {@code toKey} is null |
2210 |
* @throws IllegalArgumentException {@inheritDoc} |
2211 |
*/ |
2212 |
public ConcurrentNavigableMap<K,V> subMap(K fromKey, |
2213 |
boolean fromInclusive, |
2214 |
K toKey, |
2215 |
boolean toInclusive) { |
2216 |
if (fromKey == null || toKey == null) |
2217 |
throw new NullPointerException(); |
2218 |
return new SubMap<K,V> |
2219 |
(this, fromKey, fromInclusive, toKey, toInclusive, false); |
2220 |
} |
2221 |
|
2222 |
/** |
2223 |
* @throws ClassCastException {@inheritDoc} |
2224 |
* @throws NullPointerException if {@code toKey} is null |
2225 |
* @throws IllegalArgumentException {@inheritDoc} |
2226 |
*/ |
2227 |
public ConcurrentNavigableMap<K,V> headMap(K toKey, |
2228 |
boolean inclusive) { |
2229 |
if (toKey == null) |
2230 |
throw new NullPointerException(); |
2231 |
return new SubMap<K,V> |
2232 |
(this, null, false, toKey, inclusive, false); |
2233 |
} |
2234 |
|
2235 |
/** |
2236 |
* @throws ClassCastException {@inheritDoc} |
2237 |
* @throws NullPointerException if {@code fromKey} is null |
2238 |
* @throws IllegalArgumentException {@inheritDoc} |
2239 |
*/ |
2240 |
public ConcurrentNavigableMap<K,V> tailMap(K fromKey, |
2241 |
boolean inclusive) { |
2242 |
if (fromKey == null) |
2243 |
throw new NullPointerException(); |
2244 |
return new SubMap<K,V> |
2245 |
(this, fromKey, inclusive, null, false, false); |
2246 |
} |
2247 |
|
2248 |
/** |
2249 |
* @throws ClassCastException {@inheritDoc} |
2250 |
* @throws NullPointerException if {@code fromKey} or {@code toKey} is null |
2251 |
* @throws IllegalArgumentException {@inheritDoc} |
2252 |
*/ |
2253 |
public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) { |
2254 |
return subMap(fromKey, true, toKey, false); |
2255 |
} |
2256 |
|
2257 |
/** |
2258 |
* @throws ClassCastException {@inheritDoc} |
2259 |
* @throws NullPointerException if {@code toKey} is null |
2260 |
* @throws IllegalArgumentException {@inheritDoc} |
2261 |
*/ |
2262 |
public ConcurrentNavigableMap<K,V> headMap(K toKey) { |
2263 |
return headMap(toKey, false); |
2264 |
} |
2265 |
|
2266 |
/** |
2267 |
* @throws ClassCastException {@inheritDoc} |
2268 |
* @throws NullPointerException if {@code fromKey} is null |
2269 |
* @throws IllegalArgumentException {@inheritDoc} |
2270 |
*/ |
2271 |
public ConcurrentNavigableMap<K,V> tailMap(K fromKey) { |
2272 |
return tailMap(fromKey, true); |
2273 |
} |
2274 |
|
2275 |
/* ---------------- Relational operations -------------- */ |
2276 |
|
2277 |
/** |
2278 |
* Returns a key-value mapping associated with the greatest key |
2279 |
* strictly less than the given key, or {@code null} if there is |
2280 |
* no such key. The returned entry does <em>not</em> support the |
2281 |
* {@code Entry.setValue} method. |
2282 |
* |
2283 |
* @throws ClassCastException {@inheritDoc} |
2284 |
* @throws NullPointerException if the specified key is null |
2285 |
*/ |
2286 |
public Map.Entry<K,V> lowerEntry(K key) { |
2287 |
return getNear(key, LT); |
2288 |
} |
2289 |
|
2290 |
/** |
2291 |
* @throws ClassCastException {@inheritDoc} |
2292 |
* @throws NullPointerException if the specified key is null |
2293 |
*/ |
2294 |
public K lowerKey(K key) { |
2295 |
Comparator<? super K> cmp; |
2296 |
Node<K,V> n = findNear(key, LT); |
2297 |
return (n == null) ? null : n.key; |
2298 |
} |
2299 |
|
2300 |
/** |
2301 |
* Returns a key-value mapping associated with the greatest key |
2302 |
* less than or equal to the given key, or {@code null} if there |
2303 |
* is no such key. The returned entry does <em>not</em> support |
2304 |
* the {@code Entry.setValue} method. |
2305 |
* |
2306 |
* @param key the key |
2307 |
* @throws ClassCastException {@inheritDoc} |
2308 |
* @throws NullPointerException if the specified key is null |
2309 |
*/ |
2310 |
public Map.Entry<K,V> floorEntry(K key) { |
2311 |
return getNear(key, LT|EQ); |
2312 |
} |
2313 |
|
2314 |
/** |
2315 |
* @param key the key |
2316 |
* @throws ClassCastException {@inheritDoc} |
2317 |
* @throws NullPointerException if the specified key is null |
2318 |
*/ |
2319 |
public K floorKey(K key) { |
2320 |
Node<K,V> n = findNear(key, LT|EQ); |
2321 |
return (n == null) ? null : n.key; |
2322 |
} |
2323 |
|
2324 |
/** |
2325 |
* Returns a key-value mapping associated with the least key |
2326 |
* greater than or equal to the given key, or {@code null} if |
2327 |
* there is no such entry. The returned entry does <em>not</em> |
2328 |
* support the {@code Entry.setValue} method. |
2329 |
* |
2330 |
* @throws ClassCastException {@inheritDoc} |
2331 |
* @throws NullPointerException if the specified key is null |
2332 |
*/ |
2333 |
public Map.Entry<K,V> ceilingEntry(K key) { |
2334 |
return getNear(key, GT|EQ); |
2335 |
} |
2336 |
|
2337 |
/** |
2338 |
* @throws ClassCastException {@inheritDoc} |
2339 |
* @throws NullPointerException if the specified key is null |
2340 |
*/ |
2341 |
public K ceilingKey(K key) { |
2342 |
Node<K,V> n = findNear(key, GT|EQ); |
2343 |
return (n == null) ? null : n.key; |
2344 |
} |
2345 |
|
2346 |
/** |
2347 |
* Returns a key-value mapping associated with the least key |
2348 |
* strictly greater than the given key, or {@code null} if there |
2349 |
* is no such key. The returned entry does <em>not</em> support |
2350 |
* the {@code Entry.setValue} method. |
2351 |
* |
2352 |
* @param key the key |
2353 |
* @throws ClassCastException {@inheritDoc} |
2354 |
* @throws NullPointerException if the specified key is null |
2355 |
*/ |
2356 |
public Map.Entry<K,V> higherEntry(K key) { |
2357 |
return getNear(key, GT); |
2358 |
} |
2359 |
|
2360 |
/** |
2361 |
* @param key the key |
2362 |
* @throws ClassCastException {@inheritDoc} |
2363 |
* @throws NullPointerException if the specified key is null |
2364 |
*/ |
2365 |
public K higherKey(K key) { |
2366 |
Node<K,V> n = findNear(key, GT); |
2367 |
return (n == null) ? null : n.key; |
2368 |
} |
2369 |
|
2370 |
/** |
2371 |
* Returns a key-value mapping associated with the least |
2372 |
* key in this map, or {@code null} if the map is empty. |
2373 |
* The returned entry does <em>not</em> support |
2374 |
* the {@code Entry.setValue} method. |
2375 |
*/ |
2376 |
public Map.Entry<K,V> firstEntry() { |
2377 |
for (;;) { |
2378 |
Node<K,V> n = findFirst(); |
2379 |
if (n == null) |
2380 |
return null; |
2381 |
AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); |
2382 |
if (e != null) |
2383 |
return e; |
2384 |
} |
2385 |
} |
2386 |
|
2387 |
/** |
2388 |
* Returns a key-value mapping associated with the greatest |
2389 |
* key in this map, or {@code null} if the map is empty. |
2390 |
* The returned entry does <em>not</em> support |
2391 |
* the {@code Entry.setValue} method. |
2392 |
*/ |
2393 |
public Map.Entry<K,V> lastEntry() { |
2394 |
for (;;) { |
2395 |
Node<K,V> n = findLast(); |
2396 |
if (n == null) |
2397 |
return null; |
2398 |
AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot(); |
2399 |
if (e != null) |
2400 |
return e; |
2401 |
} |
2402 |
} |
2403 |
|
2404 |
/** |
2405 |
* Removes and returns a key-value mapping associated with |
2406 |
* the least key in this map, or {@code null} if the map is empty. |
2407 |
* The returned entry does <em>not</em> support |
2408 |
* the {@code Entry.setValue} method. |
2409 |
*/ |
2410 |
public Map.Entry<K,V> pollFirstEntry() { |
2411 |
return doRemoveFirstEntry(); |
2412 |
} |
2413 |
|
2414 |
/** |
2415 |
* Removes and returns a key-value mapping associated with |
2416 |
* the greatest key in this map, or {@code null} if the map is empty. |
2417 |
* The returned entry does <em>not</em> support |
2418 |
* the {@code Entry.setValue} method. |
2419 |
*/ |
2420 |
public Map.Entry<K,V> pollLastEntry() { |
2421 |
return doRemoveLastEntry(); |
2422 |
} |
2423 |
|
2424 |
|
2425 |
/* ---------------- Iterators -------------- */ |
2426 |
|
2427 |
/** |
2428 |
* Base of iterator classes: |
2429 |
*/ |
2430 |
abstract class Iter<T> implements Iterator<T> { |
2431 |
/** the last node returned by next() */ |
2432 |
Node<K,V> lastReturned; |
2433 |
/** the next node to return from next(); */ |
2434 |
Node<K,V> next; |
2435 |
/** Cache of next value field to maintain weak consistency */ |
2436 |
V nextValue; |
2437 |
|
2438 |
/** Initializes ascending iterator for entire range. */ |
2439 |
Iter() { |
2440 |
for (;;) { |
2441 |
next = findFirst(); |
2442 |
if (next == null) |
2443 |
break; |
2444 |
Object x = next.value; |
2445 |
if (x != null && x != next) { |
2446 |
nextValue = (V) x; |
2447 |
break; |
2448 |
} |
2449 |
} |
2450 |
} |
2451 |
|
2452 |
public final boolean hasNext() { |
2453 |
return next != null; |
2454 |
} |
2455 |
|
2456 |
/** Advances next to higher entry. */ |
2457 |
final void advance() { |
2458 |
if (next == null) |
2459 |
throw new NoSuchElementException(); |
2460 |
lastReturned = next; |
2461 |
for (;;) { |
2462 |
next = next.next; |
2463 |
if (next == null) |
2464 |
break; |
2465 |
Object x = next.value; |
2466 |
if (x != null && x != next) { |
2467 |
nextValue = (V) x; |
2468 |
break; |
2469 |
} |
2470 |
} |
2471 |
} |
2472 |
|
2473 |
public void remove() { |
2474 |
Node<K,V> l = lastReturned; |
2475 |
if (l == null) |
2476 |
throw new IllegalStateException(); |
2477 |
// It would not be worth all of the overhead to directly |
2478 |
// unlink from here. Using remove is fast enough. |
2479 |
ConcurrentSkipListMap.this.remove(l.key); |
2480 |
lastReturned = null; |
2481 |
} |
2482 |
|
2483 |
} |
2484 |
|
2485 |
final class ValueIterator extends Iter<V> { |
2486 |
public V next() { |
2487 |
V v = nextValue; |
2488 |
advance(); |
2489 |
return v; |
2490 |
} |
2491 |
} |
2492 |
|
2493 |
final class KeyIterator extends Iter<K> { |
2494 |
public K next() { |
2495 |
Node<K,V> n = next; |
2496 |
advance(); |
2497 |
return n.key; |
2498 |
} |
2499 |
} |
2500 |
|
2501 |
final class EntryIterator extends Iter<Map.Entry<K,V>> { |
2502 |
public Map.Entry<K,V> next() { |
2503 |
Node<K,V> n = next; |
2504 |
V v = nextValue; |
2505 |
advance(); |
2506 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
2507 |
} |
2508 |
} |
2509 |
|
2510 |
// Factory methods for iterators needed by ConcurrentSkipListSet etc |
2511 |
|
2512 |
Iterator<K> keyIterator() { |
2513 |
return new KeyIterator(); |
2514 |
} |
2515 |
|
2516 |
Iterator<V> valueIterator() { |
2517 |
return new ValueIterator(); |
2518 |
} |
2519 |
|
2520 |
Iterator<Map.Entry<K,V>> entryIterator() { |
2521 |
return new EntryIterator(); |
2522 |
} |
2523 |
|
2524 |
/* ---------------- View Classes -------------- */ |
2525 |
|
2526 |
/* |
2527 |
* View classes are static, delegating to a ConcurrentNavigableMap |
2528 |
* to allow use by SubMaps, which outweighs the ugliness of |
2529 |
* needing type-tests for Iterator methods. |
2530 |
*/ |
2531 |
|
2532 |
static final <E> List<E> toList(Collection<E> c) { |
2533 |
// Using size() here would be a pessimization. |
2534 |
ArrayList<E> list = new ArrayList<E>(); |
2535 |
for (E e : c) |
2536 |
list.add(e); |
2537 |
return list; |
2538 |
} |
2539 |
|
2540 |
static final class KeySet<E> |
2541 |
extends AbstractSet<E> implements NavigableSet<E> { |
2542 |
private final ConcurrentNavigableMap<E,?> m; |
2543 |
KeySet(ConcurrentNavigableMap<E,?> map) { m = map; } |
2544 |
public int size() { return m.size(); } |
2545 |
public boolean isEmpty() { return m.isEmpty(); } |
2546 |
public boolean contains(Object o) { return m.containsKey(o); } |
2547 |
public boolean remove(Object o) { return m.remove(o) != null; } |
2548 |
public void clear() { m.clear(); } |
2549 |
public E lower(E e) { return m.lowerKey(e); } |
2550 |
public E floor(E e) { return m.floorKey(e); } |
2551 |
public E ceiling(E e) { return m.ceilingKey(e); } |
2552 |
public E higher(E e) { return m.higherKey(e); } |
2553 |
public Comparator<? super E> comparator() { return m.comparator(); } |
2554 |
public E first() { return m.firstKey(); } |
2555 |
public E last() { return m.lastKey(); } |
2556 |
public E pollFirst() { |
2557 |
Map.Entry<E,?> e = m.pollFirstEntry(); |
2558 |
return (e == null) ? null : e.getKey(); |
2559 |
} |
2560 |
public E pollLast() { |
2561 |
Map.Entry<E,?> e = m.pollLastEntry(); |
2562 |
return (e == null) ? null : e.getKey(); |
2563 |
} |
2564 |
public Iterator<E> iterator() { |
2565 |
if (m instanceof ConcurrentSkipListMap) |
2566 |
return ((ConcurrentSkipListMap<E,Object>)m).keyIterator(); |
2567 |
else |
2568 |
return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator(); |
2569 |
} |
2570 |
public boolean equals(Object o) { |
2571 |
if (o == this) |
2572 |
return true; |
2573 |
if (!(o instanceof Set)) |
2574 |
return false; |
2575 |
Collection<?> c = (Collection<?>) o; |
2576 |
try { |
2577 |
return containsAll(c) && c.containsAll(this); |
2578 |
} catch (ClassCastException unused) { |
2579 |
return false; |
2580 |
} catch (NullPointerException unused) { |
2581 |
return false; |
2582 |
} |
2583 |
} |
2584 |
public Object[] toArray() { return toList(this).toArray(); } |
2585 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2586 |
public Iterator<E> descendingIterator() { |
2587 |
return descendingSet().iterator(); |
2588 |
} |
2589 |
public NavigableSet<E> subSet(E fromElement, |
2590 |
boolean fromInclusive, |
2591 |
E toElement, |
2592 |
boolean toInclusive) { |
2593 |
return new KeySet<E>(m.subMap(fromElement, fromInclusive, |
2594 |
toElement, toInclusive)); |
2595 |
} |
2596 |
public NavigableSet<E> headSet(E toElement, boolean inclusive) { |
2597 |
return new KeySet<E>(m.headMap(toElement, inclusive)); |
2598 |
} |
2599 |
public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { |
2600 |
return new KeySet<E>(m.tailMap(fromElement, inclusive)); |
2601 |
} |
2602 |
public NavigableSet<E> subSet(E fromElement, E toElement) { |
2603 |
return subSet(fromElement, true, toElement, false); |
2604 |
} |
2605 |
public NavigableSet<E> headSet(E toElement) { |
2606 |
return headSet(toElement, false); |
2607 |
} |
2608 |
public NavigableSet<E> tailSet(E fromElement) { |
2609 |
return tailSet(fromElement, true); |
2610 |
} |
2611 |
public NavigableSet<E> descendingSet() { |
2612 |
return new KeySet<E>(m.descendingMap()); |
2613 |
} |
2614 |
|
2615 |
public Stream<E> stream() { |
2616 |
int flags = Streams.STREAM_IS_DISTINCT | |
2617 |
Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED; |
2618 |
if (m instanceof ConcurrentSkipListMap) |
2619 |
return Streams.stream |
2620 |
(() -> ((ConcurrentSkipListMap<E,?>)m).keySpliterator(), |
2621 |
flags); |
2622 |
else |
2623 |
return Streams.stream |
2624 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2625 |
} |
2626 |
|
2627 |
public Stream<E> parallelStream() { |
2628 |
int flags = Streams.STREAM_IS_DISTINCT | |
2629 |
Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED; |
2630 |
if (m instanceof ConcurrentSkipListMap) |
2631 |
return Streams.parallelStream |
2632 |
(() -> ((ConcurrentSkipListMap<E,?>)m).keySpliterator(), |
2633 |
flags); |
2634 |
else |
2635 |
return Streams.parallelStream |
2636 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2637 |
} |
2638 |
} |
2639 |
|
2640 |
static final class Values<E> extends AbstractCollection<E> { |
2641 |
private final ConcurrentNavigableMap<?, E> m; |
2642 |
Values(ConcurrentNavigableMap<?, E> map) { |
2643 |
m = map; |
2644 |
} |
2645 |
public Iterator<E> iterator() { |
2646 |
if (m instanceof ConcurrentSkipListMap) |
2647 |
return ((ConcurrentSkipListMap<?,E>)m).valueIterator(); |
2648 |
else |
2649 |
return ((SubMap<?,E>)m).valueIterator(); |
2650 |
} |
2651 |
public boolean isEmpty() { |
2652 |
return m.isEmpty(); |
2653 |
} |
2654 |
public int size() { |
2655 |
return m.size(); |
2656 |
} |
2657 |
public boolean contains(Object o) { |
2658 |
return m.containsValue(o); |
2659 |
} |
2660 |
public void clear() { |
2661 |
m.clear(); |
2662 |
} |
2663 |
public Object[] toArray() { return toList(this).toArray(); } |
2664 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2665 |
|
2666 |
public Stream<E> stream() { |
2667 |
int flags = Streams.STREAM_IS_ORDERED; |
2668 |
if (m instanceof ConcurrentSkipListMap) |
2669 |
return Streams.stream |
2670 |
(() -> ((ConcurrentSkipListMap<?,E>)m).valueSpliterator(), |
2671 |
flags); |
2672 |
else |
2673 |
return Streams.stream |
2674 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2675 |
} |
2676 |
|
2677 |
public Stream<E> parallelStream() { |
2678 |
int flags = Streams.STREAM_IS_ORDERED; |
2679 |
if (m instanceof ConcurrentSkipListMap) |
2680 |
return Streams.parallelStream |
2681 |
(() -> ((ConcurrentSkipListMap<?,E>)m).valueSpliterator(), |
2682 |
flags); |
2683 |
else |
2684 |
return Streams.parallelStream |
2685 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2686 |
} |
2687 |
} |
2688 |
|
2689 |
static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> { |
2690 |
private final ConcurrentNavigableMap<K1, V1> m; |
2691 |
EntrySet(ConcurrentNavigableMap<K1, V1> map) { |
2692 |
m = map; |
2693 |
} |
2694 |
|
2695 |
public Iterator<Map.Entry<K1,V1>> iterator() { |
2696 |
if (m instanceof ConcurrentSkipListMap) |
2697 |
return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator(); |
2698 |
else |
2699 |
return ((SubMap<K1,V1>)m).entryIterator(); |
2700 |
} |
2701 |
|
2702 |
public boolean contains(Object o) { |
2703 |
if (!(o instanceof Map.Entry)) |
2704 |
return false; |
2705 |
Map.Entry<?,?> e = (Map.Entry<?,?>)o; |
2706 |
V1 v = m.get(e.getKey()); |
2707 |
return v != null && v.equals(e.getValue()); |
2708 |
} |
2709 |
public boolean remove(Object o) { |
2710 |
if (!(o instanceof Map.Entry)) |
2711 |
return false; |
2712 |
Map.Entry<?,?> e = (Map.Entry<?,?>)o; |
2713 |
return m.remove(e.getKey(), |
2714 |
e.getValue()); |
2715 |
} |
2716 |
public boolean isEmpty() { |
2717 |
return m.isEmpty(); |
2718 |
} |
2719 |
public int size() { |
2720 |
return m.size(); |
2721 |
} |
2722 |
public void clear() { |
2723 |
m.clear(); |
2724 |
} |
2725 |
public boolean equals(Object o) { |
2726 |
if (o == this) |
2727 |
return true; |
2728 |
if (!(o instanceof Set)) |
2729 |
return false; |
2730 |
Collection<?> c = (Collection<?>) o; |
2731 |
try { |
2732 |
return containsAll(c) && c.containsAll(this); |
2733 |
} catch (ClassCastException unused) { |
2734 |
return false; |
2735 |
} catch (NullPointerException unused) { |
2736 |
return false; |
2737 |
} |
2738 |
} |
2739 |
public Object[] toArray() { return toList(this).toArray(); } |
2740 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
2741 |
|
2742 |
@Override public Stream<Map.Entry<K1,V1>> stream() { |
2743 |
int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_DISTINCT; |
2744 |
if (m instanceof ConcurrentSkipListMap) |
2745 |
return Streams.stream |
2746 |
(() -> ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator(), |
2747 |
flags); |
2748 |
else |
2749 |
return Streams.stream |
2750 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2751 |
} |
2752 |
|
2753 |
public Stream<Map.Entry<K1,V1>> parallelStream() { |
2754 |
int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_DISTINCT; |
2755 |
if (m instanceof ConcurrentSkipListMap) |
2756 |
return Streams.parallelStream |
2757 |
(() -> ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator(), |
2758 |
flags); |
2759 |
else |
2760 |
return Streams.parallelStream |
2761 |
(Streams.spliteratorUnknownSize(iterator()), flags); |
2762 |
} |
2763 |
|
2764 |
} |
2765 |
|
2766 |
/** |
2767 |
* Submaps returned by {@link ConcurrentSkipListMap} submap operations |
2768 |
* represent a subrange of mappings of their underlying |
2769 |
* maps. Instances of this class support all methods of their |
2770 |
* underlying maps, differing in that mappings outside their range are |
2771 |
* ignored, and attempts to add mappings outside their ranges result |
2772 |
* in {@link IllegalArgumentException}. Instances of this class are |
2773 |
* constructed only using the {@code subMap}, {@code headMap}, and |
2774 |
* {@code tailMap} methods of their underlying maps. |
2775 |
* |
2776 |
* @serial include |
2777 |
*/ |
2778 |
static final class SubMap<K,V> extends AbstractMap<K,V> |
2779 |
implements ConcurrentNavigableMap<K,V>, Cloneable, |
2780 |
java.io.Serializable { |
2781 |
private static final long serialVersionUID = -7647078645895051609L; |
2782 |
|
2783 |
/** Underlying map */ |
2784 |
private final ConcurrentSkipListMap<K,V> m; |
2785 |
/** lower bound key, or null if from start */ |
2786 |
private final K lo; |
2787 |
/** upper bound key, or null if to end */ |
2788 |
private final K hi; |
2789 |
/** inclusion flag for lo */ |
2790 |
private final boolean loInclusive; |
2791 |
/** inclusion flag for hi */ |
2792 |
private final boolean hiInclusive; |
2793 |
/** direction */ |
2794 |
private final boolean isDescending; |
2795 |
|
2796 |
// Lazily initialized view holders |
2797 |
private transient KeySet<K> keySetView; |
2798 |
private transient Set<Map.Entry<K,V>> entrySetView; |
2799 |
private transient Collection<V> valuesView; |
2800 |
|
2801 |
/** |
2802 |
* Creates a new submap, initializing all fields. |
2803 |
*/ |
2804 |
SubMap(ConcurrentSkipListMap<K,V> map, |
2805 |
K fromKey, boolean fromInclusive, |
2806 |
K toKey, boolean toInclusive, |
2807 |
boolean isDescending) { |
2808 |
if (fromKey != null && toKey != null && |
2809 |
map.compare(fromKey, toKey) > 0) |
2810 |
throw new IllegalArgumentException("inconsistent range"); |
2811 |
this.m = map; |
2812 |
this.lo = fromKey; |
2813 |
this.hi = toKey; |
2814 |
this.loInclusive = fromInclusive; |
2815 |
this.hiInclusive = toInclusive; |
2816 |
this.isDescending = isDescending; |
2817 |
} |
2818 |
|
2819 |
/* ---------------- Utilities -------------- */ |
2820 |
|
2821 |
private boolean tooLow(K key) { |
2822 |
if (lo != null) { |
2823 |
int c = m.compare(key, lo); |
2824 |
if (c < 0 || (c == 0 && !loInclusive)) |
2825 |
return true; |
2826 |
} |
2827 |
return false; |
2828 |
} |
2829 |
|
2830 |
private boolean tooHigh(K key) { |
2831 |
if (hi != null) { |
2832 |
int c = m.compare(key, hi); |
2833 |
if (c > 0 || (c == 0 && !hiInclusive)) |
2834 |
return true; |
2835 |
} |
2836 |
return false; |
2837 |
} |
2838 |
|
2839 |
private boolean inBounds(K key) { |
2840 |
return !tooLow(key) && !tooHigh(key); |
2841 |
} |
2842 |
|
2843 |
private void checkKeyBounds(K key) throws IllegalArgumentException { |
2844 |
if (key == null) |
2845 |
throw new NullPointerException(); |
2846 |
if (!inBounds(key)) |
2847 |
throw new IllegalArgumentException("key out of range"); |
2848 |
} |
2849 |
|
2850 |
/** |
2851 |
* Returns true if node key is less than upper bound of range. |
2852 |
*/ |
2853 |
private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) { |
2854 |
if (n == null) |
2855 |
return false; |
2856 |
if (hi == null) |
2857 |
return true; |
2858 |
K k = n.key; |
2859 |
if (k == null) // pass by markers and headers |
2860 |
return true; |
2861 |
int c = m.compare(k, hi); |
2862 |
if (c > 0 || (c == 0 && !hiInclusive)) |
2863 |
return false; |
2864 |
return true; |
2865 |
} |
2866 |
|
2867 |
/** |
2868 |
* Returns lowest node. This node might not be in range, so |
2869 |
* most usages need to check bounds. |
2870 |
*/ |
2871 |
private ConcurrentSkipListMap.Node<K,V> loNode() { |
2872 |
if (lo == null) |
2873 |
return m.findFirst(); |
2874 |
else if (loInclusive) |
2875 |
return m.findNear(lo, GT|EQ); |
2876 |
else |
2877 |
return m.findNear(lo, GT); |
2878 |
} |
2879 |
|
2880 |
/** |
2881 |
* Returns highest node. This node might not be in range, so |
2882 |
* most usages need to check bounds. |
2883 |
*/ |
2884 |
private ConcurrentSkipListMap.Node<K,V> hiNode() { |
2885 |
if (hi == null) |
2886 |
return m.findLast(); |
2887 |
else if (hiInclusive) |
2888 |
return m.findNear(hi, LT|EQ); |
2889 |
else |
2890 |
return m.findNear(hi, LT); |
2891 |
} |
2892 |
|
2893 |
/** |
2894 |
* Returns lowest absolute key (ignoring directonality). |
2895 |
*/ |
2896 |
private K lowestKey() { |
2897 |
ConcurrentSkipListMap.Node<K,V> n = loNode(); |
2898 |
if (isBeforeEnd(n)) |
2899 |
return n.key; |
2900 |
else |
2901 |
throw new NoSuchElementException(); |
2902 |
} |
2903 |
|
2904 |
/** |
2905 |
* Returns highest absolute key (ignoring directonality). |
2906 |
*/ |
2907 |
private K highestKey() { |
2908 |
ConcurrentSkipListMap.Node<K,V> n = hiNode(); |
2909 |
if (n != null) { |
2910 |
K last = n.key; |
2911 |
if (inBounds(last)) |
2912 |
return last; |
2913 |
} |
2914 |
throw new NoSuchElementException(); |
2915 |
} |
2916 |
|
2917 |
private Map.Entry<K,V> lowestEntry() { |
2918 |
for (;;) { |
2919 |
ConcurrentSkipListMap.Node<K,V> n = loNode(); |
2920 |
if (!isBeforeEnd(n)) |
2921 |
return null; |
2922 |
Map.Entry<K,V> e = n.createSnapshot(); |
2923 |
if (e != null) |
2924 |
return e; |
2925 |
} |
2926 |
} |
2927 |
|
2928 |
private Map.Entry<K,V> highestEntry() { |
2929 |
for (;;) { |
2930 |
ConcurrentSkipListMap.Node<K,V> n = hiNode(); |
2931 |
if (n == null || !inBounds(n.key)) |
2932 |
return null; |
2933 |
Map.Entry<K,V> e = n.createSnapshot(); |
2934 |
if (e != null) |
2935 |
return e; |
2936 |
} |
2937 |
} |
2938 |
|
2939 |
private Map.Entry<K,V> removeLowest() { |
2940 |
for (;;) { |
2941 |
Node<K,V> n = loNode(); |
2942 |
if (n == null) |
2943 |
return null; |
2944 |
K k = n.key; |
2945 |
if (!inBounds(k)) |
2946 |
return null; |
2947 |
V v = (m.comparator == null) ? m.doRemove(k, null) : |
2948 |
m.doRemoveCmp(m.comparator, k, null); |
2949 |
if (v != null) |
2950 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2951 |
} |
2952 |
} |
2953 |
|
2954 |
private Map.Entry<K,V> removeHighest() { |
2955 |
for (;;) { |
2956 |
Node<K,V> n = hiNode(); |
2957 |
if (n == null) |
2958 |
return null; |
2959 |
K k = n.key; |
2960 |
if (!inBounds(k)) |
2961 |
return null; |
2962 |
V v = (m.comparator == null) ? m.doRemove(k, null) : |
2963 |
m.doRemoveCmp(m.comparator, k, null); |
2964 |
if (v != null) |
2965 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2966 |
} |
2967 |
} |
2968 |
|
2969 |
/** |
2970 |
* Submap version of ConcurrentSkipListMap.getNearEntry |
2971 |
*/ |
2972 |
private Map.Entry<K,V> getNearEntry(K key, int rel) { |
2973 |
if (isDescending) { // adjust relation for direction |
2974 |
if ((rel & LT) == 0) |
2975 |
rel |= LT; |
2976 |
else |
2977 |
rel &= ~LT; |
2978 |
} |
2979 |
if (tooLow(key)) |
2980 |
return ((rel & LT) != 0) ? null : lowestEntry(); |
2981 |
if (tooHigh(key)) |
2982 |
return ((rel & LT) != 0) ? highestEntry() : null; |
2983 |
for (;;) { |
2984 |
Node<K,V> n = m.findNear(key, rel); |
2985 |
if (n == null || !inBounds(n.key)) |
2986 |
return null; |
2987 |
K k = n.key; |
2988 |
V v = n.getValidValue(); |
2989 |
if (v != null) |
2990 |
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v); |
2991 |
} |
2992 |
} |
2993 |
|
2994 |
// Almost the same as getNearEntry, except for keys |
2995 |
private K getNearKey(K key, int rel) { |
2996 |
if (isDescending) { // adjust relation for direction |
2997 |
if ((rel & LT) == 0) |
2998 |
rel |= LT; |
2999 |
else |
3000 |
rel &= ~LT; |
3001 |
} |
3002 |
if (tooLow(key)) { |
3003 |
if ((rel & LT) == 0) { |
3004 |
ConcurrentSkipListMap.Node<K,V> n = loNode(); |
3005 |
if (isBeforeEnd(n)) |
3006 |
return n.key; |
3007 |
} |
3008 |
return null; |
3009 |
} |
3010 |
if (tooHigh(key)) { |
3011 |
if ((rel & LT) != 0) { |
3012 |
ConcurrentSkipListMap.Node<K,V> n = hiNode(); |
3013 |
if (n != null) { |
3014 |
K last = n.key; |
3015 |
if (inBounds(last)) |
3016 |
return last; |
3017 |
} |
3018 |
} |
3019 |
return null; |
3020 |
} |
3021 |
for (;;) { |
3022 |
Node<K,V> n = m.findNear(key, rel); |
3023 |
if (n == null || !inBounds(n.key)) |
3024 |
return null; |
3025 |
K k = n.key; |
3026 |
V v = n.getValidValue(); |
3027 |
if (v != null) |
3028 |
return k; |
3029 |
} |
3030 |
} |
3031 |
|
3032 |
/* ---------------- Map API methods -------------- */ |
3033 |
|
3034 |
public boolean containsKey(Object key) { |
3035 |
if (key == null) throw new NullPointerException(); |
3036 |
K k = (K)key; |
3037 |
return inBounds(k) && m.containsKey(k); |
3038 |
} |
3039 |
|
3040 |
public V get(Object key) { |
3041 |
if (key == null) throw new NullPointerException(); |
3042 |
K k = (K)key; |
3043 |
return (!inBounds(k)) ? null : m.get(k); |
3044 |
} |
3045 |
|
3046 |
public V put(K key, V value) { |
3047 |
checkKeyBounds(key); |
3048 |
return m.put(key, value); |
3049 |
} |
3050 |
|
3051 |
public V remove(Object key) { |
3052 |
K k = (K)key; |
3053 |
return (!inBounds(k)) ? null : m.remove(k); |
3054 |
} |
3055 |
|
3056 |
public int size() { |
3057 |
long count = 0; |
3058 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(); |
3059 |
isBeforeEnd(n); |
3060 |
n = n.next) { |
3061 |
if (n.getValidValue() != null) |
3062 |
++count; |
3063 |
} |
3064 |
return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count; |
3065 |
} |
3066 |
|
3067 |
public boolean isEmpty() { |
3068 |
return !isBeforeEnd(loNode()); |
3069 |
} |
3070 |
|
3071 |
public boolean containsValue(Object value) { |
3072 |
if (value == null) |
3073 |
throw new NullPointerException(); |
3074 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(); |
3075 |
isBeforeEnd(n); |
3076 |
n = n.next) { |
3077 |
V v = n.getValidValue(); |
3078 |
if (v != null && value.equals(v)) |
3079 |
return true; |
3080 |
} |
3081 |
return false; |
3082 |
} |
3083 |
|
3084 |
public void clear() { |
3085 |
for (ConcurrentSkipListMap.Node<K,V> n = loNode(); |
3086 |
isBeforeEnd(n); |
3087 |
n = n.next) { |
3088 |
if (n.getValidValue() != null) |
3089 |
m.remove(n.key); |
3090 |
} |
3091 |
} |
3092 |
|
3093 |
/* ---------------- ConcurrentMap API methods -------------- */ |
3094 |
|
3095 |
public V putIfAbsent(K key, V value) { |
3096 |
checkKeyBounds(key); |
3097 |
return m.putIfAbsent(key, value); |
3098 |
} |
3099 |
|
3100 |
public boolean remove(Object key, Object value) { |
3101 |
K k = (K)key; |
3102 |
return inBounds(k) && m.remove(k, value); |
3103 |
} |
3104 |
|
3105 |
public boolean replace(K key, V oldValue, V newValue) { |
3106 |
checkKeyBounds(key); |
3107 |
return m.replace(key, oldValue, newValue); |
3108 |
} |
3109 |
|
3110 |
public V replace(K key, V value) { |
3111 |
checkKeyBounds(key); |
3112 |
return m.replace(key, value); |
3113 |
} |
3114 |
|
3115 |
/* ---------------- SortedMap API methods -------------- */ |
3116 |
|
3117 |
public Comparator<? super K> comparator() { |
3118 |
Comparator<? super K> cmp = m.comparator(); |
3119 |
if (isDescending) |
3120 |
return Collections.reverseOrder(cmp); |
3121 |
else |
3122 |
return cmp; |
3123 |
} |
3124 |
|
3125 |
/** |
3126 |
* Utility to create submaps, where given bounds override |
3127 |
* unbounded(null) ones and/or are checked against bounded ones. |
3128 |
*/ |
3129 |
private SubMap<K,V> newSubMap(K fromKey, |
3130 |
boolean fromInclusive, |
3131 |
K toKey, |
3132 |
boolean toInclusive) { |
3133 |
if (isDescending) { // flip senses |
3134 |
K tk = fromKey; |
3135 |
fromKey = toKey; |
3136 |
toKey = tk; |
3137 |
boolean ti = fromInclusive; |
3138 |
fromInclusive = toInclusive; |
3139 |
toInclusive = ti; |
3140 |
} |
3141 |
if (lo != null) { |
3142 |
if (fromKey == null) { |
3143 |
fromKey = lo; |
3144 |
fromInclusive = loInclusive; |
3145 |
} |
3146 |
else { |
3147 |
int c = m.compare(fromKey, lo); |
3148 |
if (c < 0 || (c == 0 && !loInclusive && fromInclusive)) |
3149 |
throw new IllegalArgumentException("key out of range"); |
3150 |
} |
3151 |
} |
3152 |
if (hi != null) { |
3153 |
if (toKey == null) { |
3154 |
toKey = hi; |
3155 |
toInclusive = hiInclusive; |
3156 |
} |
3157 |
else { |
3158 |
int c = m.compare(toKey, hi); |
3159 |
if (c > 0 || (c == 0 && !hiInclusive && toInclusive)) |
3160 |
throw new IllegalArgumentException("key out of range"); |
3161 |
} |
3162 |
} |
3163 |
return new SubMap<K,V>(m, fromKey, fromInclusive, |
3164 |
toKey, toInclusive, isDescending); |
3165 |
} |
3166 |
|
3167 |
public SubMap<K,V> subMap(K fromKey, |
3168 |
boolean fromInclusive, |
3169 |
K toKey, |
3170 |
boolean toInclusive) { |
3171 |
if (fromKey == null || toKey == null) |
3172 |
throw new NullPointerException(); |
3173 |
return newSubMap(fromKey, fromInclusive, toKey, toInclusive); |
3174 |
} |
3175 |
|
3176 |
public SubMap<K,V> headMap(K toKey, |
3177 |
boolean inclusive) { |
3178 |
if (toKey == null) |
3179 |
throw new NullPointerException(); |
3180 |
return newSubMap(null, false, toKey, inclusive); |
3181 |
} |
3182 |
|
3183 |
public SubMap<K,V> tailMap(K fromKey, |
3184 |
boolean inclusive) { |
3185 |
if (fromKey == null) |
3186 |
throw new NullPointerException(); |
3187 |
return newSubMap(fromKey, inclusive, null, false); |
3188 |
} |
3189 |
|
3190 |
public SubMap<K,V> subMap(K fromKey, K toKey) { |
3191 |
return subMap(fromKey, true, toKey, false); |
3192 |
} |
3193 |
|
3194 |
public SubMap<K,V> headMap(K toKey) { |
3195 |
return headMap(toKey, false); |
3196 |
} |
3197 |
|
3198 |
public SubMap<K,V> tailMap(K fromKey) { |
3199 |
return tailMap(fromKey, true); |
3200 |
} |
3201 |
|
3202 |
public SubMap<K,V> descendingMap() { |
3203 |
return new SubMap<K,V>(m, lo, loInclusive, |
3204 |
hi, hiInclusive, !isDescending); |
3205 |
} |
3206 |
|
3207 |
/* ---------------- Relational methods -------------- */ |
3208 |
|
3209 |
public Map.Entry<K,V> ceilingEntry(K key) { |
3210 |
return getNearEntry(key, GT|EQ); |
3211 |
} |
3212 |
|
3213 |
public K ceilingKey(K key) { |
3214 |
return getNearKey(key, GT|EQ); |
3215 |
} |
3216 |
|
3217 |
public Map.Entry<K,V> lowerEntry(K key) { |
3218 |
return getNearEntry(key, LT); |
3219 |
} |
3220 |
|
3221 |
public K lowerKey(K key) { |
3222 |
return getNearKey(key, LT); |
3223 |
} |
3224 |
|
3225 |
public Map.Entry<K,V> floorEntry(K key) { |
3226 |
return getNearEntry(key, LT|EQ); |
3227 |
} |
3228 |
|
3229 |
public K floorKey(K key) { |
3230 |
return getNearKey(key, LT|EQ); |
3231 |
} |
3232 |
|
3233 |
public Map.Entry<K,V> higherEntry(K key) { |
3234 |
return getNearEntry(key, GT); |
3235 |
} |
3236 |
|
3237 |
public K higherKey(K key) { |
3238 |
return getNearKey(key, GT); |
3239 |
} |
3240 |
|
3241 |
public K firstKey() { |
3242 |
return isDescending ? highestKey() : lowestKey(); |
3243 |
} |
3244 |
|
3245 |
public K lastKey() { |
3246 |
return isDescending ? lowestKey() : highestKey(); |
3247 |
} |
3248 |
|
3249 |
public Map.Entry<K,V> firstEntry() { |
3250 |
return isDescending ? highestEntry() : lowestEntry(); |
3251 |
} |
3252 |
|
3253 |
public Map.Entry<K,V> lastEntry() { |
3254 |
return isDescending ? lowestEntry() : highestEntry(); |
3255 |
} |
3256 |
|
3257 |
public Map.Entry<K,V> pollFirstEntry() { |
3258 |
return isDescending ? removeHighest() : removeLowest(); |
3259 |
} |
3260 |
|
3261 |
public Map.Entry<K,V> pollLastEntry() { |
3262 |
return isDescending ? removeLowest() : removeHighest(); |
3263 |
} |
3264 |
|
3265 |
/* ---------------- Submap Views -------------- */ |
3266 |
|
3267 |
public NavigableSet<K> keySet() { |
3268 |
KeySet<K> ks = keySetView; |
3269 |
return (ks != null) ? ks : (keySetView = new KeySet<K>(this)); |
3270 |
} |
3271 |
|
3272 |
public NavigableSet<K> navigableKeySet() { |
3273 |
KeySet<K> ks = keySetView; |
3274 |
return (ks != null) ? ks : (keySetView = new KeySet<K>(this)); |
3275 |
} |
3276 |
|
3277 |
public Collection<V> values() { |
3278 |
Collection<V> vs = valuesView; |
3279 |
return (vs != null) ? vs : (valuesView = new Values<V>(this)); |
3280 |
} |
3281 |
|
3282 |
public Set<Map.Entry<K,V>> entrySet() { |
3283 |
Set<Map.Entry<K,V>> es = entrySetView; |
3284 |
return (es != null) ? es : (entrySetView = new EntrySet<K,V>(this)); |
3285 |
} |
3286 |
|
3287 |
public NavigableSet<K> descendingKeySet() { |
3288 |
return descendingMap().navigableKeySet(); |
3289 |
} |
3290 |
|
3291 |
Iterator<K> keyIterator() { |
3292 |
return new SubMapKeyIterator(); |
3293 |
} |
3294 |
|
3295 |
Iterator<V> valueIterator() { |
3296 |
return new SubMapValueIterator(); |
3297 |
} |
3298 |
|
3299 |
Iterator<Map.Entry<K,V>> entryIterator() { |
3300 |
return new SubMapEntryIterator(); |
3301 |
} |
3302 |
|
3303 |
/** |
3304 |
* Variant of main Iter class to traverse through submaps. |
3305 |
*/ |
3306 |
abstract class SubMapIter<T> implements Iterator<T> { |
3307 |
/** the last node returned by next() */ |
3308 |
Node<K,V> lastReturned; |
3309 |
/** the next node to return from next(); */ |
3310 |
Node<K,V> next; |
3311 |
/** Cache of next value field to maintain weak consistency */ |
3312 |
V nextValue; |
3313 |
|
3314 |
SubMapIter() { |
3315 |
for (;;) { |
3316 |
next = isDescending ? hiNode() : loNode(); |
3317 |
if (next == null) |
3318 |
break; |
3319 |
Object x = next.value; |
3320 |
if (x != null && x != next) { |
3321 |
if (! inBounds(next.key)) |
3322 |
next = null; |
3323 |
else |
3324 |
nextValue = (V) x; |
3325 |
break; |
3326 |
} |
3327 |
} |
3328 |
} |
3329 |
|
3330 |
public final boolean hasNext() { |
3331 |
return next != null; |
3332 |
} |
3333 |
|
3334 |
final void advance() { |
3335 |
if (next == null) |
3336 |
throw new NoSuchElementException(); |
3337 |
lastReturned = next; |
3338 |
if (isDescending) |
3339 |
descend(); |
3340 |
else |
3341 |
ascend(); |
3342 |
} |
3343 |
|
3344 |
private void ascend() { |
3345 |
for (;;) { |
3346 |
next = next.next; |
3347 |
if (next == null) |
3348 |
break; |
3349 |
Object x = next.value; |
3350 |
if (x != null && x != next) { |
3351 |
if (tooHigh(next.key)) |
3352 |
next = null; |
3353 |
else |
3354 |
nextValue = (V) x; |
3355 |
break; |
3356 |
} |
3357 |
} |
3358 |
} |
3359 |
|
3360 |
private void descend() { |
3361 |
Comparator<? super K> cmp = m.comparator; |
3362 |
for (;;) { |
3363 |
next = (cmp == null) ? m.doFindNear(lastReturned.key, LT) : |
3364 |
m.doFindNearCmp(cmp, lastReturned.key, LT); |
3365 |
if (next == null) |
3366 |
break; |
3367 |
Object x = next.value; |
3368 |
if (x != null && x != next) { |
3369 |
if (tooLow(next.key)) |
3370 |
next = null; |
3371 |
else |
3372 |
nextValue = (V) x; |
3373 |
break; |
3374 |
} |
3375 |
} |
3376 |
} |
3377 |
|
3378 |
public void remove() { |
3379 |
Node<K,V> l = lastReturned; |
3380 |
if (l == null) |
3381 |
throw new IllegalStateException(); |
3382 |
m.remove(l.key); |
3383 |
lastReturned = null; |
3384 |
} |
3385 |
|
3386 |
} |
3387 |
|
3388 |
final class SubMapValueIterator extends SubMapIter<V> { |
3389 |
public V next() { |
3390 |
V v = nextValue; |
3391 |
advance(); |
3392 |
return v; |
3393 |
} |
3394 |
} |
3395 |
|
3396 |
final class SubMapKeyIterator extends SubMapIter<K> { |
3397 |
public K next() { |
3398 |
Node<K,V> n = next; |
3399 |
advance(); |
3400 |
return n.key; |
3401 |
} |
3402 |
} |
3403 |
|
3404 |
final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> { |
3405 |
public Map.Entry<K,V> next() { |
3406 |
Node<K,V> n = next; |
3407 |
V v = nextValue; |
3408 |
advance(); |
3409 |
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v); |
3410 |
} |
3411 |
} |
3412 |
} |
3413 |
|
3414 |
/** |
3415 |
* A view of a ConcurrentSkipListMap as a {@link Set} of keys, in |
3416 |
* which additions may optionally be enabled by mapping to a |
3417 |
* common value. This class cannot be directly instantiated. See |
3418 |
* {@link #keySet()}, {@link #keySet(Object)}, {@link #newKeySet()}, |
3419 |
* {@link #newKeySet(Comparator)}. |
3420 |
*/ |
3421 |
public static class KeySetView<K,V> extends AbstractSet<K> |
3422 |
implements NavigableSet<K>, java.io.Serializable { |
3423 |
|
3424 |
/* |
3425 |
* This class overlaps in functionality with the |
3426 |
* relative-scoped KeySet class, but must be distinct and |
3427 |
* unrelated. So we repeat most of the boring delegation code. |
3428 |
*/ |
3429 |
|
3430 |
private static final long serialVersionUID = 7249069246763182397L; |
3431 |
private final ConcurrentSkipListMap<K,V> m; |
3432 |
private final V value; |
3433 |
|
3434 |
KeySetView(ConcurrentSkipListMap<K,V> map, V value) { // non-public |
3435 |
this.m = map; |
3436 |
this.value = value; |
3437 |
} |
3438 |
|
3439 |
/** |
3440 |
* Returns the map backing this view. |
3441 |
* |
3442 |
* @return the map backing this view |
3443 |
*/ |
3444 |
public ConcurrentSkipListMap<K,V> getMap() { return m; } |
3445 |
|
3446 |
/** |
3447 |
* Returns the default mapped value for additions, |
3448 |
* or {@code null} if additions are not supported. |
3449 |
* |
3450 |
* @return the default mapped value for additions, or {@code null} |
3451 |
* if not supported |
3452 |
*/ |
3453 |
public V getMappedValue() { return value; } |
3454 |
|
3455 |
public boolean add(K e) { |
3456 |
V v; |
3457 |
if ((v = value) == null) |
3458 |
throw new UnsupportedOperationException(); |
3459 |
if (e == null) |
3460 |
throw new NullPointerException(); |
3461 |
return m.put(e, v) == null; |
3462 |
} |
3463 |
|
3464 |
public boolean addAll(Collection<? extends K> c) { |
3465 |
boolean added = false; |
3466 |
V v; |
3467 |
if ((v = value) == null) |
3468 |
throw new UnsupportedOperationException(); |
3469 |
for (K e : c) { |
3470 |
if (e == null) |
3471 |
throw new NullPointerException(); |
3472 |
if (m.put(e, v) == null) |
3473 |
added = true; |
3474 |
} |
3475 |
return added; |
3476 |
} |
3477 |
|
3478 |
public int size() { return m.size(); } |
3479 |
public boolean isEmpty() { return m.isEmpty(); } |
3480 |
public boolean contains(Object o) { return m.containsKey(o); } |
3481 |
public boolean remove(Object o) { return m.remove(o) != null; } |
3482 |
public void clear() { m.clear(); } |
3483 |
public K lower(K e) { return m.lowerKey(e); } |
3484 |
public K floor(K e) { return m.floorKey(e); } |
3485 |
public K ceiling(K e) { return m.ceilingKey(e); } |
3486 |
public K higher(K e) { return m.higherKey(e); } |
3487 |
public Comparator<? super K> comparator() { return m.comparator(); } |
3488 |
public K first() { return m.firstKey(); } |
3489 |
public K last() { return m.lastKey(); } |
3490 |
public Iterator<K> iterator() { return m.keyIterator(); } |
3491 |
public K pollFirst() { |
3492 |
Map.Entry<K,?> e = m.pollFirstEntry(); |
3493 |
return (e == null) ? null : e.getKey(); |
3494 |
} |
3495 |
public K pollLast() { |
3496 |
Map.Entry<K,?> e = m.pollLastEntry(); |
3497 |
return (e == null) ? null : e.getKey(); |
3498 |
} |
3499 |
public boolean equals(Object o) { |
3500 |
if (o == this) |
3501 |
return true; |
3502 |
if (!(o instanceof Set)) |
3503 |
return false; |
3504 |
Collection<?> c = (Collection<?>) o; |
3505 |
try { |
3506 |
return containsAll(c) && c.containsAll(this); |
3507 |
} catch (ClassCastException unused) { |
3508 |
return false; |
3509 |
} catch (NullPointerException unused) { |
3510 |
return false; |
3511 |
} |
3512 |
} |
3513 |
public Object[] toArray() { return toList(this).toArray(); } |
3514 |
public <T> T[] toArray(T[] a) { return toList(this).toArray(a); } |
3515 |
public Iterator<K> descendingIterator() { |
3516 |
return descendingSet().iterator(); |
3517 |
} |
3518 |
public NavigableSet<K> subSet(K fromElement, |
3519 |
boolean fromInclusive, |
3520 |
K toElement, |
3521 |
boolean toInclusive) { |
3522 |
return new KeySet<K>(m.subMap(fromElement, fromInclusive, |
3523 |
toElement, toInclusive)); |
3524 |
} |
3525 |
public NavigableSet<K> headSet(K toElement, boolean inclusive) { |
3526 |
return new KeySet<K>(m.headMap(toElement, inclusive)); |
3527 |
} |
3528 |
public NavigableSet<K> tailSet(K fromElement, boolean inclusive) { |
3529 |
return new KeySet<K>(m.tailMap(fromElement, inclusive)); |
3530 |
} |
3531 |
public NavigableSet<K> subSet(K fromElement, K toElement) { |
3532 |
return subSet(fromElement, true, toElement, false); |
3533 |
} |
3534 |
public NavigableSet<K> headSet(K toElement) { |
3535 |
return headSet(toElement, false); |
3536 |
} |
3537 |
public NavigableSet<K> tailSet(K fromElement) { |
3538 |
return tailSet(fromElement, true); |
3539 |
} |
3540 |
public NavigableSet<K> descendingSet() { |
3541 |
return new KeySet<K>(m.descendingMap()); |
3542 |
} |
3543 |
|
3544 |
public Stream<K> stream() { |
3545 |
int flags = Streams.STREAM_IS_DISTINCT | |
3546 |
Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED; |
3547 |
return Streams.stream(() -> m.keySpliterator(), flags); |
3548 |
} |
3549 |
|
3550 |
public Stream<K> parallelStream() { |
3551 |
int flags = Streams.STREAM_IS_DISTINCT | |
3552 |
Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED; |
3553 |
return Streams.parallelStream(() -> m.keySpliterator(), flags); |
3554 |
} |
3555 |
|
3556 |
} |
3557 |
|
3558 |
/** |
3559 |
* Base class providing common structure for Spliterators. |
3560 |
* (Although not all that much common functionality; as usual for |
3561 |
* view classes, details annoyingly vary in key, value, and entry |
3562 |
* subclasses in ways that are not worth abstracting out for |
3563 |
* internal classes.) |
3564 |
* |
3565 |
* The basic split strategy is to recursively descend from top |
3566 |
* level, row by row, descending to next row when either split |
3567 |
* off, or the end of row is encountered. Control of the number of |
3568 |
* splits relies on some statistical estimation: The expected |
3569 |
* remaining number of elements of a skip list when advancing |
3570 |
* either across or down decreases by about 25%. To make this |
3571 |
* observation useful, we need to know initial size, which we |
3572 |
* don't. But we use (1 << 2*levels) as a rough overestimate that |
3573 |
* minimizes risk of prematurely zeroing out while splitting. |
3574 |
*/ |
3575 |
static class CSLMSpliterator<K,V> { |
3576 |
final Comparator<? super K> comparator; |
3577 |
final K fence; // exclusive upper bound for keys, or null if to end |
3578 |
Index<K,V> row; // the level to split out |
3579 |
Node<K,V> current; // current traversal node; initialize at origin |
3580 |
int est; // pseudo-size estimate |
3581 |
|
3582 |
CSLMSpliterator(ConcurrentSkipListMap<K,V> m) { |
3583 |
HeadIndex<K,V> h; Node<K,V> p; int d, n; Index<K,V> hd; |
3584 |
this.comparator = m.comparator; |
3585 |
this.fence = null; |
3586 |
for (;;) { // ensure h and n correspond to origin p |
3587 |
Node<K,V> b = (h = m.head).node; |
3588 |
if ((p = b.next) == null) { |
3589 |
n = 0; |
3590 |
break; |
3591 |
} |
3592 |
if (p.value != null) { |
3593 |
n = (d = h.level << 1) >= 31 ? Integer.MAX_VALUE : 1 << d; |
3594 |
break; |
3595 |
} |
3596 |
p.helpDelete(b, p.next); |
3597 |
} |
3598 |
this.est = n; |
3599 |
this.current = p; |
3600 |
this.row = (h.right == null && (hd = h.down) != null) ? hd : h; |
3601 |
} |
3602 |
|
3603 |
CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3604 |
Node<K,V> origin, K fence, int est) { |
3605 |
this.comparator = comparator; this.row = row; |
3606 |
this.current = origin; this.fence = fence; this.est = est; |
3607 |
} |
3608 |
|
3609 |
/** Return >= 0 if key is too large (out of bounds) */ |
3610 |
final int compareBounds(K k) { |
3611 |
Comparator<? super K> cmp; K f; |
3612 |
if (k == null || (f = fence) == null) |
3613 |
return -1; |
3614 |
else if ((cmp = comparator) != null) |
3615 |
return cmp.compare(k, f); |
3616 |
else |
3617 |
return ((Comparable<? super K>)k).compareTo(f); |
3618 |
} |
3619 |
|
3620 |
public final long estimateSize() { return (long)est; } |
3621 |
public final boolean hasExactSize() { |
3622 |
return est == 0 && current == null; // true only if empty |
3623 |
} |
3624 |
public final boolean hasExactSplits() { return false; } |
3625 |
} |
3626 |
|
3627 |
// factory methods |
3628 |
final KeySpliterator<K,V> keySpliterator() { |
3629 |
return new KeySpliterator<K,V>(this); |
3630 |
} |
3631 |
|
3632 |
final ValueSpliterator<K,V> valueSpliterator() { |
3633 |
return new ValueSpliterator<K,V>(this); |
3634 |
} |
3635 |
|
3636 |
final EntrySpliterator<K,V> entrySpliterator() { |
3637 |
return new EntrySpliterator<K,V>(this); |
3638 |
} |
3639 |
|
3640 |
static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V> |
3641 |
implements Spliterator<K> { |
3642 |
KeySpliterator(ConcurrentSkipListMap<K,V> m) { super(m); } |
3643 |
KeySpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3644 |
Node<K,V> origin, K fence, int est) { |
3645 |
super(comparator, row, origin, fence, est); |
3646 |
} |
3647 |
|
3648 |
public KeySpliterator<K,V> trySplit() { |
3649 |
Node<K,V> e; |
3650 |
Comparator<? super K> cmp = comparator; |
3651 |
K f = fence; |
3652 |
if ((e = current) != null) { |
3653 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3654 |
Index<K,V> s; Node<K,V> n; K sk; |
3655 |
est -= est >>> 2; |
3656 |
if ((s = q.right) != null) { |
3657 |
for (;;) { |
3658 |
Node<K,V> b = s.node; |
3659 |
if ((n = b.next) == null || n.value != null) |
3660 |
break; |
3661 |
n.helpDelete(b, n.next); |
3662 |
} |
3663 |
if (n != null && (sk = n.key) != null && |
3664 |
(f == null || |
3665 |
(cmp != null ? (cmp.compare(f, sk) > 0) : |
3666 |
(((Comparable<? super K>)f).compareTo(sk) > 0)))) { |
3667 |
current = n; |
3668 |
Index<K,V> r = q.down; |
3669 |
row = (s.right != null) ? s : s.down; |
3670 |
return new KeySpliterator<K,V>(cmp, r, e, sk, est); |
3671 |
} |
3672 |
} |
3673 |
} |
3674 |
} |
3675 |
return null; |
3676 |
} |
3677 |
|
3678 |
public void forEach(Consumer<? super K> block) { |
3679 |
if (block == null) throw new NullPointerException(); |
3680 |
K f = fence; |
3681 |
Comparator<? super K> cmp = comparator; |
3682 |
Comparable<? super K> cf = (f != null && cmp == null) ? |
3683 |
(Comparable<? super K>)f : null; |
3684 |
Node<K,V> e = current; |
3685 |
current = null; |
3686 |
for (; e != null; e = e.next) { |
3687 |
K k; Object v; |
3688 |
if ((k = e.key) != null && |
3689 |
(cf != null ? (cf.compareTo(k) <= 0) : |
3690 |
(f != null && cmp.compare(f, k) <= 0))) |
3691 |
break; |
3692 |
if ((v = e.value) != null && v != e) |
3693 |
block.accept(k); |
3694 |
} |
3695 |
} |
3696 |
|
3697 |
public boolean tryAdvance(Consumer<? super K> block) { |
3698 |
if (block == null) throw new NullPointerException(); |
3699 |
Node<K,V> e; |
3700 |
for (e = current; e != null; e = e.next) { |
3701 |
K k; Object v; |
3702 |
if (compareBounds(k = e.key) >= 0) { |
3703 |
e = null; |
3704 |
break; |
3705 |
} |
3706 |
if ((v = e.value) != null && v != e) { |
3707 |
current = e.next; |
3708 |
block.accept(k); |
3709 |
return true; |
3710 |
} |
3711 |
} |
3712 |
current = e; |
3713 |
return false; |
3714 |
} |
3715 |
} |
3716 |
|
3717 |
static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V> |
3718 |
implements Spliterator<V> { |
3719 |
ValueSpliterator(ConcurrentSkipListMap<K,V> m) { super(m); } |
3720 |
ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3721 |
Node<K,V> origin, K fence, int est) { |
3722 |
super(comparator, row, origin, fence, est); |
3723 |
} |
3724 |
|
3725 |
public ValueSpliterator<K,V> trySplit() { |
3726 |
Node<K,V> e; |
3727 |
Comparator<? super K> cmp = comparator; |
3728 |
K f = fence; |
3729 |
if ((e = current) != null) { |
3730 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3731 |
Index<K,V> s; Node<K,V> n; K sk; |
3732 |
est -= est >>> 2; |
3733 |
if ((s = q.right) != null) { |
3734 |
for (;;) { |
3735 |
Node<K,V> b = s.node; |
3736 |
if ((n = b.next) == null || n.value != null) |
3737 |
break; |
3738 |
n.helpDelete(b, n.next); |
3739 |
} |
3740 |
if (n != null && (sk = n.key) != null && |
3741 |
(f == null || |
3742 |
(cmp != null ? (cmp.compare(f, sk) > 0) : |
3743 |
(((Comparable<? super K>)f).compareTo(sk) > 0)))) { |
3744 |
current = n; |
3745 |
Index<K,V> r = q.down; |
3746 |
row = (s.right != null) ? s : s.down; |
3747 |
return new ValueSpliterator<K,V>(cmp, r, e, sk, est); |
3748 |
} |
3749 |
} |
3750 |
} |
3751 |
} |
3752 |
return null; |
3753 |
} |
3754 |
|
3755 |
public void forEach(Consumer<? super V> block) { |
3756 |
if (block == null) throw new NullPointerException(); |
3757 |
K f = fence; |
3758 |
Comparator<? super K> cmp = comparator; |
3759 |
Comparable<? super K> cf = (f != null && cmp == null) ? |
3760 |
(Comparable<? super K>)f : null; |
3761 |
Node<K,V> e = current; |
3762 |
current = null; |
3763 |
for (; e != null; e = e.next) { |
3764 |
K k; Object v; |
3765 |
if ((k = e.key) != null && |
3766 |
(cf != null ? (cf.compareTo(k) <= 0) : |
3767 |
(f != null && cmp.compare(f, k) <= 0))) |
3768 |
break; |
3769 |
if ((v = e.value) != null && v != e) |
3770 |
block.accept((V)v); |
3771 |
} |
3772 |
} |
3773 |
|
3774 |
public boolean tryAdvance(Consumer<? super V> block) { |
3775 |
if (block == null) throw new NullPointerException(); |
3776 |
boolean advanced = false; |
3777 |
Node<K,V> e; |
3778 |
for (e = current; e != null; e = e.next) { |
3779 |
K k; Object v; |
3780 |
if (compareBounds(k = e.key) >= 0) { |
3781 |
e = null; |
3782 |
break; |
3783 |
} |
3784 |
if ((v = e.value) != null && v != e) { |
3785 |
current = e.next; |
3786 |
block.accept((V)v); |
3787 |
return true; |
3788 |
} |
3789 |
} |
3790 |
current = e; |
3791 |
return false; |
3792 |
} |
3793 |
} |
3794 |
|
3795 |
static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V> |
3796 |
implements Spliterator<Map.Entry<K,V>> { |
3797 |
EntrySpliterator(ConcurrentSkipListMap<K,V> m) { super(m); } |
3798 |
EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row, |
3799 |
Node<K,V> origin, K fence, int est) { |
3800 |
super(comparator, row, origin, fence, est); |
3801 |
} |
3802 |
|
3803 |
public EntrySpliterator<K,V> trySplit() { |
3804 |
Node<K,V> e; |
3805 |
Comparator<? super K> cmp = comparator; |
3806 |
K f = fence; |
3807 |
if ((e = current) != null) { |
3808 |
for (Index<K,V> q = row; q != null; q = row = q.down) { |
3809 |
Index<K,V> s; Node<K,V> n; K sk; |
3810 |
est -= est >>> 2; |
3811 |
if ((s = q.right) != null) { |
3812 |
for (;;) { |
3813 |
Node<K,V> b = s.node; |
3814 |
if ((n = b.next) == null || n.value != null) |
3815 |
break; |
3816 |
n.helpDelete(b, n.next); |
3817 |
} |
3818 |
if (n != null && (sk = n.key) != null && |
3819 |
(f == null || |
3820 |
(cmp != null ? |
3821 |
(cmp.compare(f, sk) > 0) : |
3822 |
(((Comparable<? super K>)f).compareTo(sk) > 0)))) { |
3823 |
current = n; |
3824 |
Index<K,V> r = q.down; |
3825 |
row = (s.right != null) ? s : s.down; |
3826 |
return new EntrySpliterator<K,V>(cmp, r, e, sk, est); |
3827 |
} |
3828 |
} |
3829 |
} |
3830 |
} |
3831 |
return null; |
3832 |
} |
3833 |
|
3834 |
public void forEach(Consumer<? super Map.Entry<K,V>> block) { |
3835 |
if (block == null) throw new NullPointerException(); |
3836 |
K f = fence; |
3837 |
Comparator<? super K> cmp = comparator; |
3838 |
Comparable<? super K> cf = (f != null && cmp == null) ? |
3839 |
(Comparable<? super K>)f : null; |
3840 |
Node<K,V> e = current; |
3841 |
current = null; |
3842 |
for (; e != null; e = e.next) { |
3843 |
K k; Object v; |
3844 |
if ((k = e.key) != null && |
3845 |
(cf != null ? |
3846 |
(cf.compareTo(k) <= 0) : |
3847 |
(f != null && cmp.compare(f, k) <= 0))) |
3848 |
break; |
3849 |
if ((v = e.value) != null && v != e) |
3850 |
block.accept |
3851 |
(new AbstractMap.SimpleImmutableEntry<K,V>(k, (V)v)); |
3852 |
} |
3853 |
} |
3854 |
|
3855 |
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> block) { |
3856 |
if (block == null) throw new NullPointerException(); |
3857 |
Node<K,V> e; |
3858 |
for (e = current; e != null; e = e.next) { |
3859 |
K k; Object v; |
3860 |
if (compareBounds(k = e.key) >= 0) { |
3861 |
e = null; |
3862 |
break; |
3863 |
} |
3864 |
if ((v = e.value) != null && v != e) { |
3865 |
current = e.next; |
3866 |
block.accept |
3867 |
(new AbstractMap.SimpleImmutableEntry<K,V>(k, (V)v)); |
3868 |
return true; |
3869 |
} |
3870 |
} |
3871 |
current = e; |
3872 |
return false; |
3873 |
} |
3874 |
} |
3875 |
|
3876 |
// Unsafe mechanics |
3877 |
private static final sun.misc.Unsafe UNSAFE; |
3878 |
private static final long headOffset; |
3879 |
private static final long SECONDARY; |
3880 |
static { |
3881 |
try { |
3882 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
3883 |
Class<?> k = ConcurrentSkipListMap.class; |
3884 |
headOffset = UNSAFE.objectFieldOffset |
3885 |
(k.getDeclaredField("head")); |
3886 |
Class<?> tk = Thread.class; |
3887 |
SECONDARY = UNSAFE.objectFieldOffset |
3888 |
(tk.getDeclaredField("threadLocalRandomSecondarySeed")); |
3889 |
|
3890 |
} catch (Exception e) { |
3891 |
throw new Error(e); |
3892 |
} |
3893 |
} |
3894 |
} |