ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.93
Committed: Mon Jan 28 22:34:06 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.92: +1 -1 lines
Log Message:
remove bad @param

File Contents

# Content
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.Block;
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}). This is of
1979 * course only appropriate if it is acceptable to use the same
1980 * value for all additions from this view.
1981 *
1982 * @param mappedValue the mapped value to use for any
1983 * additions.
1984 * @return the set view
1985 * @throws NullPointerException if the mappedValue is null
1986 */
1987 public KeySetView<K,V> keySet(V mappedValue) {
1988 if (mappedValue == null)
1989 throw new NullPointerException();
1990 return new KeySetView<K,V>(this, mappedValue);
1991 }
1992
1993 /**
1994 * Returns a {@link Collection} view of the values contained in this map.
1995 * The collection's iterator returns the values in ascending order
1996 * of the corresponding keys.
1997 * The collection is backed by the map, so changes to the map are
1998 * reflected in the collection, and vice-versa. The collection
1999 * supports element removal, which removes the corresponding
2000 * mapping from the map, via the {@code Iterator.remove},
2001 * {@code Collection.remove}, {@code removeAll},
2002 * {@code retainAll} and {@code clear} operations. It does not
2003 * support the {@code add} or {@code addAll} operations.
2004 *
2005 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2006 * that will never throw {@link ConcurrentModificationException},
2007 * and guarantees to traverse elements as they existed upon
2008 * construction of the iterator, and may (but is not guaranteed to)
2009 * reflect any modifications subsequent to construction.
2010 */
2011 public Collection<V> values() {
2012 Values<V> vs = values;
2013 return (vs != null) ? vs : (values = new Values<V>(this));
2014 }
2015
2016 /**
2017 * Returns a {@link Set} view of the mappings contained in this map.
2018 * The set's iterator returns the entries in ascending key order.
2019 * The set is backed by the map, so changes to the map are
2020 * reflected in the set, and vice-versa. The set supports element
2021 * removal, which removes the corresponding mapping from the map,
2022 * via the {@code Iterator.remove}, {@code Set.remove},
2023 * {@code removeAll}, {@code retainAll} and {@code clear}
2024 * operations. It does not support the {@code add} or
2025 * {@code addAll} operations.
2026 *
2027 * <p>The view's {@code iterator} is a "weakly consistent" iterator
2028 * that will never throw {@link ConcurrentModificationException},
2029 * and guarantees to traverse elements as they existed upon
2030 * construction of the iterator, and may (but is not guaranteed to)
2031 * reflect any modifications subsequent to construction.
2032 *
2033 * <p>The {@code Map.Entry} elements returned by
2034 * {@code iterator.next()} do <em>not</em> support the
2035 * {@code setValue} operation.
2036 *
2037 * @return a set view of the mappings contained in this map,
2038 * sorted in ascending key order
2039 */
2040 public Set<Map.Entry<K,V>> entrySet() {
2041 EntrySet<K,V> es = entrySet;
2042 return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
2043 }
2044
2045 public ConcurrentNavigableMap<K,V> descendingMap() {
2046 ConcurrentNavigableMap<K,V> dm = descendingMap;
2047 return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
2048 (this, null, false, null, false, true));
2049 }
2050
2051 public NavigableSet<K> descendingKeySet() {
2052 return descendingMap().navigableKeySet();
2053 }
2054
2055 /* ---------------- AbstractMap Overrides -------------- */
2056
2057 /**
2058 * Compares the specified object with this map for equality.
2059 * Returns {@code true} if the given object is also a map and the
2060 * two maps represent the same mappings. More formally, two maps
2061 * {@code m1} and {@code m2} represent the same mappings if
2062 * {@code m1.entrySet().equals(m2.entrySet())}. This
2063 * operation may return misleading results if either map is
2064 * concurrently modified during execution of this method.
2065 *
2066 * @param o object to be compared for equality with this map
2067 * @return {@code true} if the specified object is equal to this map
2068 */
2069 public boolean equals(Object o) {
2070 if (o == this)
2071 return true;
2072 if (!(o instanceof Map))
2073 return false;
2074 Map<?,?> m = (Map<?,?>) o;
2075 try {
2076 for (Map.Entry<K,V> e : this.entrySet())
2077 if (! e.getValue().equals(m.get(e.getKey())))
2078 return false;
2079 for (Map.Entry<?,?> e : m.entrySet()) {
2080 Object k = e.getKey();
2081 Object v = e.getValue();
2082 if (k == null || v == null || !v.equals(get(k)))
2083 return false;
2084 }
2085 return true;
2086 } catch (ClassCastException unused) {
2087 return false;
2088 } catch (NullPointerException unused) {
2089 return false;
2090 }
2091 }
2092
2093 /* ------ ConcurrentMap API methods ------ */
2094
2095 /**
2096 * {@inheritDoc}
2097 *
2098 * @return the previous value associated with the specified key,
2099 * or {@code null} if there was no mapping for the key
2100 * @throws ClassCastException if the specified key cannot be compared
2101 * with the keys currently in the map
2102 * @throws NullPointerException if the specified key or value is null
2103 */
2104 public V putIfAbsent(K key, V value) {
2105 Comparator<? super K> cmp;
2106 if (value == null)
2107 throw new NullPointerException();
2108 return ((cmp = comparator) == null) ?
2109 doPut(key, value, true) : doPutCmp(cmp, key, value, true);
2110 }
2111
2112 /**
2113 * {@inheritDoc}
2114 *
2115 * @throws ClassCastException if the specified key cannot be compared
2116 * with the keys currently in the map
2117 * @throws NullPointerException if the specified key is null
2118 */
2119 public boolean remove(Object key, Object value) {
2120 if (key == null)
2121 throw new NullPointerException();
2122 if (value == null)
2123 return false;
2124 Comparator<? super K> cmp;
2125 Object v = ((cmp = comparator) == null) ? doRemove(key, value) :
2126 doRemoveCmp(cmp, key, value);
2127 return v != null;
2128 }
2129
2130 /**
2131 * {@inheritDoc}
2132 *
2133 * @throws ClassCastException if the specified key cannot be compared
2134 * with the keys currently in the map
2135 * @throws NullPointerException if any of the arguments are null
2136 */
2137 public boolean replace(K key, V oldValue, V newValue) {
2138 if (oldValue == null || newValue == null)
2139 throw new NullPointerException();
2140 Comparator<? super K> cmp = comparator;
2141 for (;;) {
2142 Node<K,V> n = (cmp == null) ?
2143 findNode((Comparable<? super K>)key) :
2144 findNodeCmp(cmp, key);
2145 if (n == null)
2146 return false;
2147 Object v = n.value;
2148 if (v != null) {
2149 if (!oldValue.equals(v))
2150 return false;
2151 if (n.casValue(v, newValue))
2152 return true;
2153 }
2154 }
2155 }
2156
2157 /**
2158 * {@inheritDoc}
2159 *
2160 * @return the previous value associated with the specified key,
2161 * or {@code null} if there was no mapping for the key
2162 * @throws ClassCastException if the specified key cannot be compared
2163 * with the keys currently in the map
2164 * @throws NullPointerException if the specified key or value is null
2165 */
2166 public V replace(K key, V value) {
2167 if (value == null)
2168 throw new NullPointerException();
2169 Comparator<? super K> cmp = comparator;
2170 for (;;) {
2171 Node<K,V> n = (cmp == null) ?
2172 findNode((Comparable<? super K>)key) :
2173 findNodeCmp(cmp, key);
2174 if (n == null)
2175 return null;
2176 Object v = n.value;
2177 if (v != null && n.casValue(v, value))
2178 return (V)v;
2179 }
2180 }
2181
2182 /* ------ SortedMap API methods ------ */
2183
2184 public Comparator<? super K> comparator() {
2185 return comparator;
2186 }
2187
2188 /**
2189 * @throws NoSuchElementException {@inheritDoc}
2190 */
2191 public K firstKey() {
2192 Node<K,V> n = findFirst();
2193 if (n == null)
2194 throw new NoSuchElementException();
2195 return n.key;
2196 }
2197
2198 /**
2199 * @throws NoSuchElementException {@inheritDoc}
2200 */
2201 public K lastKey() {
2202 Node<K,V> n = findLast();
2203 if (n == null)
2204 throw new NoSuchElementException();
2205 return n.key;
2206 }
2207
2208 /**
2209 * @throws ClassCastException {@inheritDoc}
2210 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2211 * @throws IllegalArgumentException {@inheritDoc}
2212 */
2213 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
2214 boolean fromInclusive,
2215 K toKey,
2216 boolean toInclusive) {
2217 if (fromKey == null || toKey == null)
2218 throw new NullPointerException();
2219 return new SubMap<K,V>
2220 (this, fromKey, fromInclusive, toKey, toInclusive, false);
2221 }
2222
2223 /**
2224 * @throws ClassCastException {@inheritDoc}
2225 * @throws NullPointerException if {@code toKey} is null
2226 * @throws IllegalArgumentException {@inheritDoc}
2227 */
2228 public ConcurrentNavigableMap<K,V> headMap(K toKey,
2229 boolean inclusive) {
2230 if (toKey == null)
2231 throw new NullPointerException();
2232 return new SubMap<K,V>
2233 (this, null, false, toKey, inclusive, false);
2234 }
2235
2236 /**
2237 * @throws ClassCastException {@inheritDoc}
2238 * @throws NullPointerException if {@code fromKey} is null
2239 * @throws IllegalArgumentException {@inheritDoc}
2240 */
2241 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2242 boolean inclusive) {
2243 if (fromKey == null)
2244 throw new NullPointerException();
2245 return new SubMap<K,V>
2246 (this, fromKey, inclusive, null, false, false);
2247 }
2248
2249 /**
2250 * @throws ClassCastException {@inheritDoc}
2251 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2252 * @throws IllegalArgumentException {@inheritDoc}
2253 */
2254 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2255 return subMap(fromKey, true, toKey, false);
2256 }
2257
2258 /**
2259 * @throws ClassCastException {@inheritDoc}
2260 * @throws NullPointerException if {@code toKey} is null
2261 * @throws IllegalArgumentException {@inheritDoc}
2262 */
2263 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2264 return headMap(toKey, false);
2265 }
2266
2267 /**
2268 * @throws ClassCastException {@inheritDoc}
2269 * @throws NullPointerException if {@code fromKey} is null
2270 * @throws IllegalArgumentException {@inheritDoc}
2271 */
2272 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2273 return tailMap(fromKey, true);
2274 }
2275
2276 /* ---------------- Relational operations -------------- */
2277
2278 /**
2279 * Returns a key-value mapping associated with the greatest key
2280 * strictly less than the given key, or {@code null} if there is
2281 * no such key. The returned entry does <em>not</em> support the
2282 * {@code Entry.setValue} method.
2283 *
2284 * @throws ClassCastException {@inheritDoc}
2285 * @throws NullPointerException if the specified key is null
2286 */
2287 public Map.Entry<K,V> lowerEntry(K key) {
2288 return getNear(key, LT);
2289 }
2290
2291 /**
2292 * @throws ClassCastException {@inheritDoc}
2293 * @throws NullPointerException if the specified key is null
2294 */
2295 public K lowerKey(K key) {
2296 Comparator<? super K> cmp;
2297 Node<K,V> n = findNear(key, LT);
2298 return (n == null) ? null : n.key;
2299 }
2300
2301 /**
2302 * Returns a key-value mapping associated with the greatest key
2303 * less than or equal to the given key, or {@code null} if there
2304 * is no such key. The returned entry does <em>not</em> support
2305 * the {@code Entry.setValue} method.
2306 *
2307 * @param key the key
2308 * @throws ClassCastException {@inheritDoc}
2309 * @throws NullPointerException if the specified key is null
2310 */
2311 public Map.Entry<K,V> floorEntry(K key) {
2312 return getNear(key, LT|EQ);
2313 }
2314
2315 /**
2316 * @param key the key
2317 * @throws ClassCastException {@inheritDoc}
2318 * @throws NullPointerException if the specified key is null
2319 */
2320 public K floorKey(K key) {
2321 Node<K,V> n = findNear(key, LT|EQ);
2322 return (n == null) ? null : n.key;
2323 }
2324
2325 /**
2326 * Returns a key-value mapping associated with the least key
2327 * greater than or equal to the given key, or {@code null} if
2328 * there is no such entry. The returned entry does <em>not</em>
2329 * support the {@code Entry.setValue} method.
2330 *
2331 * @throws ClassCastException {@inheritDoc}
2332 * @throws NullPointerException if the specified key is null
2333 */
2334 public Map.Entry<K,V> ceilingEntry(K key) {
2335 return getNear(key, GT|EQ);
2336 }
2337
2338 /**
2339 * @throws ClassCastException {@inheritDoc}
2340 * @throws NullPointerException if the specified key is null
2341 */
2342 public K ceilingKey(K key) {
2343 Node<K,V> n = findNear(key, GT|EQ);
2344 return (n == null) ? null : n.key;
2345 }
2346
2347 /**
2348 * Returns a key-value mapping associated with the least key
2349 * strictly greater than the given key, or {@code null} if there
2350 * is no such key. The returned entry does <em>not</em> support
2351 * the {@code Entry.setValue} method.
2352 *
2353 * @param key the key
2354 * @throws ClassCastException {@inheritDoc}
2355 * @throws NullPointerException if the specified key is null
2356 */
2357 public Map.Entry<K,V> higherEntry(K key) {
2358 return getNear(key, GT);
2359 }
2360
2361 /**
2362 * @param key the key
2363 * @throws ClassCastException {@inheritDoc}
2364 * @throws NullPointerException if the specified key is null
2365 */
2366 public K higherKey(K key) {
2367 Node<K,V> n = findNear(key, GT);
2368 return (n == null) ? null : n.key;
2369 }
2370
2371 /**
2372 * Returns a key-value mapping associated with the least
2373 * key in this map, or {@code null} if the map is empty.
2374 * The returned entry does <em>not</em> support
2375 * the {@code Entry.setValue} method.
2376 */
2377 public Map.Entry<K,V> firstEntry() {
2378 for (;;) {
2379 Node<K,V> n = findFirst();
2380 if (n == null)
2381 return null;
2382 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2383 if (e != null)
2384 return e;
2385 }
2386 }
2387
2388 /**
2389 * Returns a key-value mapping associated with the greatest
2390 * key in this map, or {@code null} if the map is empty.
2391 * The returned entry does <em>not</em> support
2392 * the {@code Entry.setValue} method.
2393 */
2394 public Map.Entry<K,V> lastEntry() {
2395 for (;;) {
2396 Node<K,V> n = findLast();
2397 if (n == null)
2398 return null;
2399 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2400 if (e != null)
2401 return e;
2402 }
2403 }
2404
2405 /**
2406 * Removes and returns a key-value mapping associated with
2407 * the least key in this map, or {@code null} if the map is empty.
2408 * The returned entry does <em>not</em> support
2409 * the {@code Entry.setValue} method.
2410 */
2411 public Map.Entry<K,V> pollFirstEntry() {
2412 return doRemoveFirstEntry();
2413 }
2414
2415 /**
2416 * Removes and returns a key-value mapping associated with
2417 * the greatest key in this map, or {@code null} if the map is empty.
2418 * The returned entry does <em>not</em> support
2419 * the {@code Entry.setValue} method.
2420 */
2421 public Map.Entry<K,V> pollLastEntry() {
2422 return doRemoveLastEntry();
2423 }
2424
2425
2426 /* ---------------- Iterators -------------- */
2427
2428 /**
2429 * Base of iterator classes:
2430 */
2431 abstract class Iter<T> implements Iterator<T> {
2432 /** the last node returned by next() */
2433 Node<K,V> lastReturned;
2434 /** the next node to return from next(); */
2435 Node<K,V> next;
2436 /** Cache of next value field to maintain weak consistency */
2437 V nextValue;
2438
2439 /** Initializes ascending iterator for entire range. */
2440 Iter() {
2441 for (;;) {
2442 next = findFirst();
2443 if (next == null)
2444 break;
2445 Object x = next.value;
2446 if (x != null && x != next) {
2447 nextValue = (V) x;
2448 break;
2449 }
2450 }
2451 }
2452
2453 public final boolean hasNext() {
2454 return next != null;
2455 }
2456
2457 /** Advances next to higher entry. */
2458 final void advance() {
2459 if (next == null)
2460 throw new NoSuchElementException();
2461 lastReturned = next;
2462 for (;;) {
2463 next = next.next;
2464 if (next == null)
2465 break;
2466 Object x = next.value;
2467 if (x != null && x != next) {
2468 nextValue = (V) x;
2469 break;
2470 }
2471 }
2472 }
2473
2474 public void remove() {
2475 Node<K,V> l = lastReturned;
2476 if (l == null)
2477 throw new IllegalStateException();
2478 // It would not be worth all of the overhead to directly
2479 // unlink from here. Using remove is fast enough.
2480 ConcurrentSkipListMap.this.remove(l.key);
2481 lastReturned = null;
2482 }
2483
2484 }
2485
2486 final class ValueIterator extends Iter<V> {
2487 public V next() {
2488 V v = nextValue;
2489 advance();
2490 return v;
2491 }
2492 }
2493
2494 final class KeyIterator extends Iter<K> {
2495 public K next() {
2496 Node<K,V> n = next;
2497 advance();
2498 return n.key;
2499 }
2500 }
2501
2502 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2503 public Map.Entry<K,V> next() {
2504 Node<K,V> n = next;
2505 V v = nextValue;
2506 advance();
2507 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2508 }
2509 }
2510
2511 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2512
2513 Iterator<K> keyIterator() {
2514 return new KeyIterator();
2515 }
2516
2517 Iterator<V> valueIterator() {
2518 return new ValueIterator();
2519 }
2520
2521 Iterator<Map.Entry<K,V>> entryIterator() {
2522 return new EntryIterator();
2523 }
2524
2525 /* ---------------- View Classes -------------- */
2526
2527 /*
2528 * View classes are static, delegating to a ConcurrentNavigableMap
2529 * to allow use by SubMaps, which outweighs the ugliness of
2530 * needing type-tests for Iterator methods.
2531 */
2532
2533 static final <E> List<E> toList(Collection<E> c) {
2534 // Using size() here would be a pessimization.
2535 ArrayList<E> list = new ArrayList<E>();
2536 for (E e : c)
2537 list.add(e);
2538 return list;
2539 }
2540
2541 static final class KeySet<E>
2542 extends AbstractSet<E> implements NavigableSet<E> {
2543 private final ConcurrentNavigableMap<E,?> m;
2544 KeySet(ConcurrentNavigableMap<E,?> map) { m = map; }
2545 public int size() { return m.size(); }
2546 public boolean isEmpty() { return m.isEmpty(); }
2547 public boolean contains(Object o) { return m.containsKey(o); }
2548 public boolean remove(Object o) { return m.remove(o) != null; }
2549 public void clear() { m.clear(); }
2550 public E lower(E e) { return m.lowerKey(e); }
2551 public E floor(E e) { return m.floorKey(e); }
2552 public E ceiling(E e) { return m.ceilingKey(e); }
2553 public E higher(E e) { return m.higherKey(e); }
2554 public Comparator<? super E> comparator() { return m.comparator(); }
2555 public E first() { return m.firstKey(); }
2556 public E last() { return m.lastKey(); }
2557 public E pollFirst() {
2558 Map.Entry<E,?> e = m.pollFirstEntry();
2559 return (e == null) ? null : e.getKey();
2560 }
2561 public E pollLast() {
2562 Map.Entry<E,?> e = m.pollLastEntry();
2563 return (e == null) ? null : e.getKey();
2564 }
2565 public Iterator<E> iterator() {
2566 if (m instanceof ConcurrentSkipListMap)
2567 return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2568 else
2569 return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2570 }
2571 public boolean equals(Object o) {
2572 if (o == this)
2573 return true;
2574 if (!(o instanceof Set))
2575 return false;
2576 Collection<?> c = (Collection<?>) o;
2577 try {
2578 return containsAll(c) && c.containsAll(this);
2579 } catch (ClassCastException unused) {
2580 return false;
2581 } catch (NullPointerException unused) {
2582 return false;
2583 }
2584 }
2585 public Object[] toArray() { return toList(this).toArray(); }
2586 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2587 public Iterator<E> descendingIterator() {
2588 return descendingSet().iterator();
2589 }
2590 public NavigableSet<E> subSet(E fromElement,
2591 boolean fromInclusive,
2592 E toElement,
2593 boolean toInclusive) {
2594 return new KeySet<E>(m.subMap(fromElement, fromInclusive,
2595 toElement, toInclusive));
2596 }
2597 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2598 return new KeySet<E>(m.headMap(toElement, inclusive));
2599 }
2600 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2601 return new KeySet<E>(m.tailMap(fromElement, inclusive));
2602 }
2603 public NavigableSet<E> subSet(E fromElement, E toElement) {
2604 return subSet(fromElement, true, toElement, false);
2605 }
2606 public NavigableSet<E> headSet(E toElement) {
2607 return headSet(toElement, false);
2608 }
2609 public NavigableSet<E> tailSet(E fromElement) {
2610 return tailSet(fromElement, true);
2611 }
2612 public NavigableSet<E> descendingSet() {
2613 return new KeySet<E>(m.descendingMap());
2614 }
2615
2616 public Stream<E> stream() {
2617 int flags = Streams.STREAM_IS_DISTINCT |
2618 Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED;
2619 if (m instanceof ConcurrentSkipListMap)
2620 return Streams.stream
2621 (() -> ((ConcurrentSkipListMap<E,?>)m).keySpliterator(),
2622 flags);
2623 else
2624 return Streams.stream
2625 (Streams.spliteratorUnknownSize(iterator()), flags);
2626 }
2627
2628 public Stream<E> parallelStream() {
2629 int flags = Streams.STREAM_IS_DISTINCT |
2630 Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED;
2631 if (m instanceof ConcurrentSkipListMap)
2632 return Streams.parallelStream
2633 (() -> ((ConcurrentSkipListMap<E,?>)m).keySpliterator(),
2634 flags);
2635 else
2636 return Streams.parallelStream
2637 (Streams.spliteratorUnknownSize(iterator()), flags);
2638 }
2639 }
2640
2641 static final class Values<E> extends AbstractCollection<E> {
2642 private final ConcurrentNavigableMap<?, E> m;
2643 Values(ConcurrentNavigableMap<?, E> map) {
2644 m = map;
2645 }
2646 public Iterator<E> iterator() {
2647 if (m instanceof ConcurrentSkipListMap)
2648 return ((ConcurrentSkipListMap<?,E>)m).valueIterator();
2649 else
2650 return ((SubMap<?,E>)m).valueIterator();
2651 }
2652 public boolean isEmpty() {
2653 return m.isEmpty();
2654 }
2655 public int size() {
2656 return m.size();
2657 }
2658 public boolean contains(Object o) {
2659 return m.containsValue(o);
2660 }
2661 public void clear() {
2662 m.clear();
2663 }
2664 public Object[] toArray() { return toList(this).toArray(); }
2665 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2666
2667 public Stream<E> stream() {
2668 int flags = Streams.STREAM_IS_ORDERED;
2669 if (m instanceof ConcurrentSkipListMap)
2670 return Streams.stream
2671 (() -> ((ConcurrentSkipListMap<?,E>)m).valueSpliterator(),
2672 flags);
2673 else
2674 return Streams.stream
2675 (Streams.spliteratorUnknownSize(iterator()), flags);
2676 }
2677
2678 public Stream<E> parallelStream() {
2679 int flags = Streams.STREAM_IS_ORDERED;
2680 if (m instanceof ConcurrentSkipListMap)
2681 return Streams.parallelStream
2682 (() -> ((ConcurrentSkipListMap<?,E>)m).valueSpliterator(),
2683 flags);
2684 else
2685 return Streams.parallelStream
2686 (Streams.spliteratorUnknownSize(iterator()), flags);
2687 }
2688 }
2689
2690 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2691 private final ConcurrentNavigableMap<K1, V1> m;
2692 EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2693 m = map;
2694 }
2695
2696 public Iterator<Map.Entry<K1,V1>> iterator() {
2697 if (m instanceof ConcurrentSkipListMap)
2698 return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2699 else
2700 return ((SubMap<K1,V1>)m).entryIterator();
2701 }
2702
2703 public boolean contains(Object o) {
2704 if (!(o instanceof Map.Entry))
2705 return false;
2706 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2707 V1 v = m.get(e.getKey());
2708 return v != null && v.equals(e.getValue());
2709 }
2710 public boolean remove(Object o) {
2711 if (!(o instanceof Map.Entry))
2712 return false;
2713 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2714 return m.remove(e.getKey(),
2715 e.getValue());
2716 }
2717 public boolean isEmpty() {
2718 return m.isEmpty();
2719 }
2720 public int size() {
2721 return m.size();
2722 }
2723 public void clear() {
2724 m.clear();
2725 }
2726 public boolean equals(Object o) {
2727 if (o == this)
2728 return true;
2729 if (!(o instanceof Set))
2730 return false;
2731 Collection<?> c = (Collection<?>) o;
2732 try {
2733 return containsAll(c) && c.containsAll(this);
2734 } catch (ClassCastException unused) {
2735 return false;
2736 } catch (NullPointerException unused) {
2737 return false;
2738 }
2739 }
2740 public Object[] toArray() { return toList(this).toArray(); }
2741 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2742
2743 @Override public Stream<Map.Entry<K1,V1>> stream() {
2744 int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_DISTINCT;
2745 if (m instanceof ConcurrentSkipListMap)
2746 return Streams.stream
2747 (() -> ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator(),
2748 flags);
2749 else
2750 return Streams.stream
2751 (Streams.spliteratorUnknownSize(iterator()), flags);
2752 }
2753
2754 public Stream<Map.Entry<K1,V1>> parallelStream() {
2755 int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_DISTINCT;
2756 if (m instanceof ConcurrentSkipListMap)
2757 return Streams.parallelStream
2758 (() -> ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator(),
2759 flags);
2760 else
2761 return Streams.parallelStream
2762 (Streams.spliteratorUnknownSize(iterator()), flags);
2763 }
2764
2765 }
2766
2767 /**
2768 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2769 * represent a subrange of mappings of their underlying
2770 * maps. Instances of this class support all methods of their
2771 * underlying maps, differing in that mappings outside their range are
2772 * ignored, and attempts to add mappings outside their ranges result
2773 * in {@link IllegalArgumentException}. Instances of this class are
2774 * constructed only using the {@code subMap}, {@code headMap}, and
2775 * {@code tailMap} methods of their underlying maps.
2776 *
2777 * @serial include
2778 */
2779 static final class SubMap<K,V> extends AbstractMap<K,V>
2780 implements ConcurrentNavigableMap<K,V>, Cloneable,
2781 java.io.Serializable {
2782 private static final long serialVersionUID = -7647078645895051609L;
2783
2784 /** Underlying map */
2785 private final ConcurrentSkipListMap<K,V> m;
2786 /** lower bound key, or null if from start */
2787 private final K lo;
2788 /** upper bound key, or null if to end */
2789 private final K hi;
2790 /** inclusion flag for lo */
2791 private final boolean loInclusive;
2792 /** inclusion flag for hi */
2793 private final boolean hiInclusive;
2794 /** direction */
2795 private final boolean isDescending;
2796
2797 // Lazily initialized view holders
2798 private transient KeySet<K> keySetView;
2799 private transient Set<Map.Entry<K,V>> entrySetView;
2800 private transient Collection<V> valuesView;
2801
2802 /**
2803 * Creates a new submap, initializing all fields.
2804 */
2805 SubMap(ConcurrentSkipListMap<K,V> map,
2806 K fromKey, boolean fromInclusive,
2807 K toKey, boolean toInclusive,
2808 boolean isDescending) {
2809 if (fromKey != null && toKey != null &&
2810 map.compare(fromKey, toKey) > 0)
2811 throw new IllegalArgumentException("inconsistent range");
2812 this.m = map;
2813 this.lo = fromKey;
2814 this.hi = toKey;
2815 this.loInclusive = fromInclusive;
2816 this.hiInclusive = toInclusive;
2817 this.isDescending = isDescending;
2818 }
2819
2820 /* ---------------- Utilities -------------- */
2821
2822 private boolean tooLow(K key) {
2823 if (lo != null) {
2824 int c = m.compare(key, lo);
2825 if (c < 0 || (c == 0 && !loInclusive))
2826 return true;
2827 }
2828 return false;
2829 }
2830
2831 private boolean tooHigh(K key) {
2832 if (hi != null) {
2833 int c = m.compare(key, hi);
2834 if (c > 0 || (c == 0 && !hiInclusive))
2835 return true;
2836 }
2837 return false;
2838 }
2839
2840 private boolean inBounds(K key) {
2841 return !tooLow(key) && !tooHigh(key);
2842 }
2843
2844 private void checkKeyBounds(K key) throws IllegalArgumentException {
2845 if (key == null)
2846 throw new NullPointerException();
2847 if (!inBounds(key))
2848 throw new IllegalArgumentException("key out of range");
2849 }
2850
2851 /**
2852 * Returns true if node key is less than upper bound of range.
2853 */
2854 private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
2855 if (n == null)
2856 return false;
2857 if (hi == null)
2858 return true;
2859 K k = n.key;
2860 if (k == null) // pass by markers and headers
2861 return true;
2862 int c = m.compare(k, hi);
2863 if (c > 0 || (c == 0 && !hiInclusive))
2864 return false;
2865 return true;
2866 }
2867
2868 /**
2869 * Returns lowest node. This node might not be in range, so
2870 * most usages need to check bounds.
2871 */
2872 private ConcurrentSkipListMap.Node<K,V> loNode() {
2873 if (lo == null)
2874 return m.findFirst();
2875 else if (loInclusive)
2876 return m.findNear(lo, GT|EQ);
2877 else
2878 return m.findNear(lo, GT);
2879 }
2880
2881 /**
2882 * Returns highest node. This node might not be in range, so
2883 * most usages need to check bounds.
2884 */
2885 private ConcurrentSkipListMap.Node<K,V> hiNode() {
2886 if (hi == null)
2887 return m.findLast();
2888 else if (hiInclusive)
2889 return m.findNear(hi, LT|EQ);
2890 else
2891 return m.findNear(hi, LT);
2892 }
2893
2894 /**
2895 * Returns lowest absolute key (ignoring directonality).
2896 */
2897 private K lowestKey() {
2898 ConcurrentSkipListMap.Node<K,V> n = loNode();
2899 if (isBeforeEnd(n))
2900 return n.key;
2901 else
2902 throw new NoSuchElementException();
2903 }
2904
2905 /**
2906 * Returns highest absolute key (ignoring directonality).
2907 */
2908 private K highestKey() {
2909 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2910 if (n != null) {
2911 K last = n.key;
2912 if (inBounds(last))
2913 return last;
2914 }
2915 throw new NoSuchElementException();
2916 }
2917
2918 private Map.Entry<K,V> lowestEntry() {
2919 for (;;) {
2920 ConcurrentSkipListMap.Node<K,V> n = loNode();
2921 if (!isBeforeEnd(n))
2922 return null;
2923 Map.Entry<K,V> e = n.createSnapshot();
2924 if (e != null)
2925 return e;
2926 }
2927 }
2928
2929 private Map.Entry<K,V> highestEntry() {
2930 for (;;) {
2931 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2932 if (n == null || !inBounds(n.key))
2933 return null;
2934 Map.Entry<K,V> e = n.createSnapshot();
2935 if (e != null)
2936 return e;
2937 }
2938 }
2939
2940 private Map.Entry<K,V> removeLowest() {
2941 for (;;) {
2942 Node<K,V> n = loNode();
2943 if (n == null)
2944 return null;
2945 K k = n.key;
2946 if (!inBounds(k))
2947 return null;
2948 V v = (m.comparator == null) ? m.doRemove(k, null) :
2949 m.doRemoveCmp(m.comparator, k, null);
2950 if (v != null)
2951 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2952 }
2953 }
2954
2955 private Map.Entry<K,V> removeHighest() {
2956 for (;;) {
2957 Node<K,V> n = hiNode();
2958 if (n == null)
2959 return null;
2960 K k = n.key;
2961 if (!inBounds(k))
2962 return null;
2963 V v = (m.comparator == null) ? m.doRemove(k, null) :
2964 m.doRemoveCmp(m.comparator, k, null);
2965 if (v != null)
2966 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2967 }
2968 }
2969
2970 /**
2971 * Submap version of ConcurrentSkipListMap.getNearEntry
2972 */
2973 private Map.Entry<K,V> getNearEntry(K key, int rel) {
2974 if (isDescending) { // adjust relation for direction
2975 if ((rel & LT) == 0)
2976 rel |= LT;
2977 else
2978 rel &= ~LT;
2979 }
2980 if (tooLow(key))
2981 return ((rel & LT) != 0) ? null : lowestEntry();
2982 if (tooHigh(key))
2983 return ((rel & LT) != 0) ? highestEntry() : null;
2984 for (;;) {
2985 Node<K,V> n = m.findNear(key, rel);
2986 if (n == null || !inBounds(n.key))
2987 return null;
2988 K k = n.key;
2989 V v = n.getValidValue();
2990 if (v != null)
2991 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2992 }
2993 }
2994
2995 // Almost the same as getNearEntry, except for keys
2996 private K getNearKey(K key, int rel) {
2997 if (isDescending) { // adjust relation for direction
2998 if ((rel & LT) == 0)
2999 rel |= LT;
3000 else
3001 rel &= ~LT;
3002 }
3003 if (tooLow(key)) {
3004 if ((rel & LT) == 0) {
3005 ConcurrentSkipListMap.Node<K,V> n = loNode();
3006 if (isBeforeEnd(n))
3007 return n.key;
3008 }
3009 return null;
3010 }
3011 if (tooHigh(key)) {
3012 if ((rel & LT) != 0) {
3013 ConcurrentSkipListMap.Node<K,V> n = hiNode();
3014 if (n != null) {
3015 K last = n.key;
3016 if (inBounds(last))
3017 return last;
3018 }
3019 }
3020 return null;
3021 }
3022 for (;;) {
3023 Node<K,V> n = m.findNear(key, rel);
3024 if (n == null || !inBounds(n.key))
3025 return null;
3026 K k = n.key;
3027 V v = n.getValidValue();
3028 if (v != null)
3029 return k;
3030 }
3031 }
3032
3033 /* ---------------- Map API methods -------------- */
3034
3035 public boolean containsKey(Object key) {
3036 if (key == null) throw new NullPointerException();
3037 K k = (K)key;
3038 return inBounds(k) && m.containsKey(k);
3039 }
3040
3041 public V get(Object key) {
3042 if (key == null) throw new NullPointerException();
3043 K k = (K)key;
3044 return (!inBounds(k)) ? null : m.get(k);
3045 }
3046
3047 public V put(K key, V value) {
3048 checkKeyBounds(key);
3049 return m.put(key, value);
3050 }
3051
3052 public V remove(Object key) {
3053 K k = (K)key;
3054 return (!inBounds(k)) ? null : m.remove(k);
3055 }
3056
3057 public int size() {
3058 long count = 0;
3059 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
3060 isBeforeEnd(n);
3061 n = n.next) {
3062 if (n.getValidValue() != null)
3063 ++count;
3064 }
3065 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
3066 }
3067
3068 public boolean isEmpty() {
3069 return !isBeforeEnd(loNode());
3070 }
3071
3072 public boolean containsValue(Object value) {
3073 if (value == null)
3074 throw new NullPointerException();
3075 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
3076 isBeforeEnd(n);
3077 n = n.next) {
3078 V v = n.getValidValue();
3079 if (v != null && value.equals(v))
3080 return true;
3081 }
3082 return false;
3083 }
3084
3085 public void clear() {
3086 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
3087 isBeforeEnd(n);
3088 n = n.next) {
3089 if (n.getValidValue() != null)
3090 m.remove(n.key);
3091 }
3092 }
3093
3094 /* ---------------- ConcurrentMap API methods -------------- */
3095
3096 public V putIfAbsent(K key, V value) {
3097 checkKeyBounds(key);
3098 return m.putIfAbsent(key, value);
3099 }
3100
3101 public boolean remove(Object key, Object value) {
3102 K k = (K)key;
3103 return inBounds(k) && m.remove(k, value);
3104 }
3105
3106 public boolean replace(K key, V oldValue, V newValue) {
3107 checkKeyBounds(key);
3108 return m.replace(key, oldValue, newValue);
3109 }
3110
3111 public V replace(K key, V value) {
3112 checkKeyBounds(key);
3113 return m.replace(key, value);
3114 }
3115
3116 /* ---------------- SortedMap API methods -------------- */
3117
3118 public Comparator<? super K> comparator() {
3119 Comparator<? super K> cmp = m.comparator();
3120 if (isDescending)
3121 return Collections.reverseOrder(cmp);
3122 else
3123 return cmp;
3124 }
3125
3126 /**
3127 * Utility to create submaps, where given bounds override
3128 * unbounded(null) ones and/or are checked against bounded ones.
3129 */
3130 private SubMap<K,V> newSubMap(K fromKey,
3131 boolean fromInclusive,
3132 K toKey,
3133 boolean toInclusive) {
3134 if (isDescending) { // flip senses
3135 K tk = fromKey;
3136 fromKey = toKey;
3137 toKey = tk;
3138 boolean ti = fromInclusive;
3139 fromInclusive = toInclusive;
3140 toInclusive = ti;
3141 }
3142 if (lo != null) {
3143 if (fromKey == null) {
3144 fromKey = lo;
3145 fromInclusive = loInclusive;
3146 }
3147 else {
3148 int c = m.compare(fromKey, lo);
3149 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
3150 throw new IllegalArgumentException("key out of range");
3151 }
3152 }
3153 if (hi != null) {
3154 if (toKey == null) {
3155 toKey = hi;
3156 toInclusive = hiInclusive;
3157 }
3158 else {
3159 int c = m.compare(toKey, hi);
3160 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
3161 throw new IllegalArgumentException("key out of range");
3162 }
3163 }
3164 return new SubMap<K,V>(m, fromKey, fromInclusive,
3165 toKey, toInclusive, isDescending);
3166 }
3167
3168 public SubMap<K,V> subMap(K fromKey,
3169 boolean fromInclusive,
3170 K toKey,
3171 boolean toInclusive) {
3172 if (fromKey == null || toKey == null)
3173 throw new NullPointerException();
3174 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
3175 }
3176
3177 public SubMap<K,V> headMap(K toKey,
3178 boolean inclusive) {
3179 if (toKey == null)
3180 throw new NullPointerException();
3181 return newSubMap(null, false, toKey, inclusive);
3182 }
3183
3184 public SubMap<K,V> tailMap(K fromKey,
3185 boolean inclusive) {
3186 if (fromKey == null)
3187 throw new NullPointerException();
3188 return newSubMap(fromKey, inclusive, null, false);
3189 }
3190
3191 public SubMap<K,V> subMap(K fromKey, K toKey) {
3192 return subMap(fromKey, true, toKey, false);
3193 }
3194
3195 public SubMap<K,V> headMap(K toKey) {
3196 return headMap(toKey, false);
3197 }
3198
3199 public SubMap<K,V> tailMap(K fromKey) {
3200 return tailMap(fromKey, true);
3201 }
3202
3203 public SubMap<K,V> descendingMap() {
3204 return new SubMap<K,V>(m, lo, loInclusive,
3205 hi, hiInclusive, !isDescending);
3206 }
3207
3208 /* ---------------- Relational methods -------------- */
3209
3210 public Map.Entry<K,V> ceilingEntry(K key) {
3211 return getNearEntry(key, GT|EQ);
3212 }
3213
3214 public K ceilingKey(K key) {
3215 return getNearKey(key, GT|EQ);
3216 }
3217
3218 public Map.Entry<K,V> lowerEntry(K key) {
3219 return getNearEntry(key, LT);
3220 }
3221
3222 public K lowerKey(K key) {
3223 return getNearKey(key, LT);
3224 }
3225
3226 public Map.Entry<K,V> floorEntry(K key) {
3227 return getNearEntry(key, LT|EQ);
3228 }
3229
3230 public K floorKey(K key) {
3231 return getNearKey(key, LT|EQ);
3232 }
3233
3234 public Map.Entry<K,V> higherEntry(K key) {
3235 return getNearEntry(key, GT);
3236 }
3237
3238 public K higherKey(K key) {
3239 return getNearKey(key, GT);
3240 }
3241
3242 public K firstKey() {
3243 return isDescending ? highestKey() : lowestKey();
3244 }
3245
3246 public K lastKey() {
3247 return isDescending ? lowestKey() : highestKey();
3248 }
3249
3250 public Map.Entry<K,V> firstEntry() {
3251 return isDescending ? highestEntry() : lowestEntry();
3252 }
3253
3254 public Map.Entry<K,V> lastEntry() {
3255 return isDescending ? lowestEntry() : highestEntry();
3256 }
3257
3258 public Map.Entry<K,V> pollFirstEntry() {
3259 return isDescending ? removeHighest() : removeLowest();
3260 }
3261
3262 public Map.Entry<K,V> pollLastEntry() {
3263 return isDescending ? removeLowest() : removeHighest();
3264 }
3265
3266 /* ---------------- Submap Views -------------- */
3267
3268 public NavigableSet<K> keySet() {
3269 KeySet<K> ks = keySetView;
3270 return (ks != null) ? ks : (keySetView = new KeySet<K>(this));
3271 }
3272
3273 public NavigableSet<K> navigableKeySet() {
3274 KeySet<K> ks = keySetView;
3275 return (ks != null) ? ks : (keySetView = new KeySet<K>(this));
3276 }
3277
3278 public Collection<V> values() {
3279 Collection<V> vs = valuesView;
3280 return (vs != null) ? vs : (valuesView = new Values<V>(this));
3281 }
3282
3283 public Set<Map.Entry<K,V>> entrySet() {
3284 Set<Map.Entry<K,V>> es = entrySetView;
3285 return (es != null) ? es : (entrySetView = new EntrySet<K,V>(this));
3286 }
3287
3288 public NavigableSet<K> descendingKeySet() {
3289 return descendingMap().navigableKeySet();
3290 }
3291
3292 Iterator<K> keyIterator() {
3293 return new SubMapKeyIterator();
3294 }
3295
3296 Iterator<V> valueIterator() {
3297 return new SubMapValueIterator();
3298 }
3299
3300 Iterator<Map.Entry<K,V>> entryIterator() {
3301 return new SubMapEntryIterator();
3302 }
3303
3304 /**
3305 * Variant of main Iter class to traverse through submaps.
3306 */
3307 abstract class SubMapIter<T> implements Iterator<T> {
3308 /** the last node returned by next() */
3309 Node<K,V> lastReturned;
3310 /** the next node to return from next(); */
3311 Node<K,V> next;
3312 /** Cache of next value field to maintain weak consistency */
3313 V nextValue;
3314
3315 SubMapIter() {
3316 for (;;) {
3317 next = isDescending ? hiNode() : loNode();
3318 if (next == null)
3319 break;
3320 Object x = next.value;
3321 if (x != null && x != next) {
3322 if (! inBounds(next.key))
3323 next = null;
3324 else
3325 nextValue = (V) x;
3326 break;
3327 }
3328 }
3329 }
3330
3331 public final boolean hasNext() {
3332 return next != null;
3333 }
3334
3335 final void advance() {
3336 if (next == null)
3337 throw new NoSuchElementException();
3338 lastReturned = next;
3339 if (isDescending)
3340 descend();
3341 else
3342 ascend();
3343 }
3344
3345 private void ascend() {
3346 for (;;) {
3347 next = next.next;
3348 if (next == null)
3349 break;
3350 Object x = next.value;
3351 if (x != null && x != next) {
3352 if (tooHigh(next.key))
3353 next = null;
3354 else
3355 nextValue = (V) x;
3356 break;
3357 }
3358 }
3359 }
3360
3361 private void descend() {
3362 Comparator<? super K> cmp = m.comparator;
3363 for (;;) {
3364 next = (cmp == null) ? m.doFindNear(lastReturned.key, LT) :
3365 m.doFindNearCmp(cmp, lastReturned.key, LT);
3366 if (next == null)
3367 break;
3368 Object x = next.value;
3369 if (x != null && x != next) {
3370 if (tooLow(next.key))
3371 next = null;
3372 else
3373 nextValue = (V) x;
3374 break;
3375 }
3376 }
3377 }
3378
3379 public void remove() {
3380 Node<K,V> l = lastReturned;
3381 if (l == null)
3382 throw new IllegalStateException();
3383 m.remove(l.key);
3384 lastReturned = null;
3385 }
3386
3387 }
3388
3389 final class SubMapValueIterator extends SubMapIter<V> {
3390 public V next() {
3391 V v = nextValue;
3392 advance();
3393 return v;
3394 }
3395 }
3396
3397 final class SubMapKeyIterator extends SubMapIter<K> {
3398 public K next() {
3399 Node<K,V> n = next;
3400 advance();
3401 return n.key;
3402 }
3403 }
3404
3405 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3406 public Map.Entry<K,V> next() {
3407 Node<K,V> n = next;
3408 V v = nextValue;
3409 advance();
3410 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3411 }
3412 }
3413 }
3414
3415 /**
3416 * A view of a ConcurrentSkipListMap as a {@link Set} of keys, in
3417 * which additions may optionally be enabled by mapping to a
3418 * common value. This class cannot be directly instantiated. See
3419 * {@link #keySet}, {@link #keySet(Object)}, {@link #newKeySet()},
3420 * {@link #newKeySet(Comparator)}.
3421 */
3422 public static class KeySetView<K,V> extends AbstractSet<K>
3423 implements NavigableSet<K>, java.io.Serializable {
3424
3425 /*
3426 * This class overlaps in functionality with the
3427 * relative-scoped KeySet class, but must be distinct and
3428 * unrelated. So we repeat most of the boring delegation code.
3429 */
3430
3431 private static final long serialVersionUID = 7249069246763182397L;
3432 private final ConcurrentSkipListMap<K, V> m;
3433 private final V value;
3434
3435 KeySetView(ConcurrentSkipListMap<K, V> map, V value) { // non-public
3436 this.m = map;
3437 this.value = value;
3438 }
3439
3440 /**
3441 * Returns the map backing this view.
3442 *
3443 * @return the map backing this view
3444 */
3445 public ConcurrentSkipListMap<K,V> getMap() { return m; }
3446
3447 /**
3448 * Returns the default mapped value for additions,
3449 * or {@code null} if additions are not supported.
3450 *
3451 * @return the default mapped value for additions, or {@code null}
3452 * if not supported.
3453 */
3454 public V getMappedValue() { return value; }
3455
3456 public boolean add(K e) {
3457 V v;
3458 if ((v = value) == null)
3459 throw new UnsupportedOperationException();
3460 if (e == null)
3461 throw new NullPointerException();
3462 return m.put(e, v) == null;
3463 }
3464
3465 public boolean addAll(Collection<? extends K> c) {
3466 boolean added = false;
3467 V v;
3468 if ((v = value) == null)
3469 throw new UnsupportedOperationException();
3470 for (K e : c) {
3471 if (e == null)
3472 throw new NullPointerException();
3473 if (m.put(e, v) == null)
3474 added = true;
3475 }
3476 return added;
3477 }
3478
3479 public int size() { return m.size(); }
3480 public boolean isEmpty() { return m.isEmpty(); }
3481 public boolean contains(Object o) { return m.containsKey(o); }
3482 public boolean remove(Object o) { return m.remove(o) != null; }
3483 public void clear() { m.clear(); }
3484 public K lower(K e) { return m.lowerKey(e); }
3485 public K floor(K e) { return m.floorKey(e); }
3486 public K ceiling(K e) { return m.ceilingKey(e); }
3487 public K higher(K e) { return m.higherKey(e); }
3488 public Comparator<? super K> comparator() { return m.comparator(); }
3489 public K first() { return m.firstKey(); }
3490 public K last() { return m.lastKey(); }
3491 public Iterator<K> iterator() { return m.keyIterator(); }
3492 public K pollFirst() {
3493 Map.Entry<K,?> e = m.pollFirstEntry();
3494 return (e == null) ? null : e.getKey();
3495 }
3496 public K pollLast() {
3497 Map.Entry<K,?> e = m.pollLastEntry();
3498 return (e == null) ? null : e.getKey();
3499 }
3500 public boolean equals(Object o) {
3501 if (o == this)
3502 return true;
3503 if (!(o instanceof Set))
3504 return false;
3505 Collection<?> c = (Collection<?>) o;
3506 try {
3507 return containsAll(c) && c.containsAll(this);
3508 } catch (ClassCastException unused) {
3509 return false;
3510 } catch (NullPointerException unused) {
3511 return false;
3512 }
3513 }
3514 public Object[] toArray() { return toList(this).toArray(); }
3515 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
3516 public Iterator<K> descendingIterator() {
3517 return descendingSet().iterator();
3518 }
3519 public NavigableSet<K> subSet(K fromElement,
3520 boolean fromInclusive,
3521 K toElement,
3522 boolean toInclusive) {
3523 return new KeySet<K>(m.subMap(fromElement, fromInclusive,
3524 toElement, toInclusive));
3525 }
3526 public NavigableSet<K> headSet(K toElement, boolean inclusive) {
3527 return new KeySet<K>(m.headMap(toElement, inclusive));
3528 }
3529 public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
3530 return new KeySet<K>(m.tailMap(fromElement, inclusive));
3531 }
3532 public NavigableSet<K> subSet(K fromElement, K toElement) {
3533 return subSet(fromElement, true, toElement, false);
3534 }
3535 public NavigableSet<K> headSet(K toElement) {
3536 return headSet(toElement, false);
3537 }
3538 public NavigableSet<K> tailSet(K fromElement) {
3539 return tailSet(fromElement, true);
3540 }
3541 public NavigableSet<K> descendingSet() {
3542 return new KeySet<K>(m.descendingMap());
3543 }
3544
3545 public Stream<K> stream() {
3546 int flags = Streams.STREAM_IS_DISTINCT |
3547 Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED;
3548 return Streams.stream(() -> m.keySpliterator(), flags);
3549 }
3550
3551 public Stream<K> parallelStream() {
3552 int flags = Streams.STREAM_IS_DISTINCT |
3553 Streams.STREAM_IS_SORTED | Streams.STREAM_IS_ORDERED;
3554 return Streams.parallelStream(() -> m.keySpliterator(), flags);
3555 }
3556
3557 }
3558
3559 /**
3560 * Base class providing common structure for Spliterators.
3561 * (Although not all that much common functionality; as usual for
3562 * view classes, details annoyingly vary in key, value, and entry
3563 * subclasses in ways that are not worth abstracting out for
3564 * internal classes.)
3565 *
3566 * The basic split strategy is to recursively descend from top
3567 * level, row by row, descending to next row when either split
3568 * off, or the end of row is encountered. Control of the number of
3569 * splits relies on some statistical estimation: The expected
3570 * remaining number of elements of a skip list when advancing
3571 * either across or down decreases by about 25%. To make this
3572 * observation useful, we need to know initial size, which we
3573 * don't. But we use (1 << 2*levels) as a rough overestimate that
3574 * minimizes risk of prematurely zeroing out while splitting.
3575 */
3576 static class CSLMSpliterator<K,V> {
3577 final Comparator<? super K> comparator;
3578 final K fence; // exclusive upper bound for keys, or null if to end
3579 Index<K,V> row; // the level to split out
3580 Node<K,V> current; // current traversal node; initialize at origin
3581 int est; // pseudo-size estimate
3582
3583 CSLMSpliterator(ConcurrentSkipListMap<K,V> m) {
3584 HeadIndex<K,V> h; Node<K,V> p; int d, n; Index<K,V> hd;
3585 this.comparator = m.comparator;
3586 this.fence = null;
3587 for (;;) { // ensure h and n correspond to origin p
3588 Node<K,V> b = (h = m.head).node;
3589 if ((p = b.next) == null) {
3590 n = 0;
3591 break;
3592 }
3593 if (p.value != null) {
3594 n = (d = h.level << 1) >= 31 ? Integer.MAX_VALUE : 1 << d;
3595 break;
3596 }
3597 p.helpDelete(b, p.next);
3598 }
3599 this.est = n;
3600 this.current = p;
3601 this.row = (h.right == null && (hd = h.down) != null) ? hd : h;
3602 }
3603
3604 CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3605 Node<K,V> origin, K fence, int est) {
3606 this.comparator = comparator; this.row = row;
3607 this.current = origin; this.fence = fence; this.est = est;
3608 }
3609
3610 /** Return >= 0 if key is too large (out of bounds) */
3611 final int compareBounds(K k) {
3612 Comparator<? super K> cmp; K f;
3613 if (k == null || (f = fence) == null)
3614 return -1;
3615 else if ((cmp = comparator) != null)
3616 return cmp.compare(k, f);
3617 else
3618 return ((Comparable<? super K>)k).compareTo(f);
3619 }
3620
3621 public final long estimateSize() { return (long)est; }
3622 public final boolean hasExactSize() {
3623 return est == 0 && current == null; // true only if empty
3624 }
3625 public final boolean hasExactSplits() { return false; }
3626 }
3627
3628 // factory methods
3629 final KeySpliterator<K,V> keySpliterator() {
3630 return new KeySpliterator<K,V>(this);
3631 }
3632
3633 final ValueSpliterator<K,V> valueSpliterator() {
3634 return new ValueSpliterator<K,V>(this);
3635 }
3636
3637 final EntrySpliterator<K,V> entrySpliterator() {
3638 return new EntrySpliterator<K,V>(this);
3639 }
3640
3641 static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
3642 implements Spliterator<K> {
3643 KeySpliterator(ConcurrentSkipListMap<K,V> m) { super(m); }
3644 KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3645 Node<K,V> origin, K fence, int est) {
3646 super(comparator, row, origin, fence, est);
3647 }
3648
3649 public KeySpliterator<K,V> trySplit() {
3650 Node<K,V> e;
3651 Comparator<? super K> cmp = comparator;
3652 K f = fence;
3653 if ((e = current) != null) {
3654 for (Index<K,V> q = row; q != null; q = row = q.down) {
3655 Index<K,V> s; Node<K,V> n; K sk;
3656 est -= est >>> 2;
3657 if ((s = q.right) != null) {
3658 for (;;) {
3659 Node<K,V> b = s.node;
3660 if ((n = b.next) == null || n.value != null)
3661 break;
3662 n.helpDelete(b, n.next);
3663 }
3664 if (n != null && (sk = n.key) != null &&
3665 (f == null ||
3666 (cmp != null ? (cmp.compare(f, sk) > 0) :
3667 (((Comparable<? super K>)f).compareTo(sk) > 0)))) {
3668 current = n;
3669 Index<K,V> r = q.down;
3670 row = (s.right != null) ? s : s.down;
3671 return new KeySpliterator<K,V>(cmp, r, e, sk, est);
3672 }
3673 }
3674 }
3675 }
3676 return null;
3677 }
3678
3679 public void forEach(Block<? super K> block) {
3680 if (block == null) throw new NullPointerException();
3681 K f = fence;
3682 Comparator<? super K> cmp = comparator;
3683 Comparable<? super K> cf = (f != null && cmp == null) ?
3684 (Comparable<? super K>)f : null;
3685 Node<K,V> e = current;
3686 current = null;
3687 for (; e != null; e = e.next) {
3688 K k; Object v;
3689 if ((k = e.key) != null &&
3690 (cf != null ? (cf.compareTo(k) <= 0) :
3691 (f != null && cmp.compare(f, k) <= 0)))
3692 break;
3693 if ((v = e.value) != null && v != e)
3694 block.accept(k);
3695 }
3696 }
3697
3698 public boolean tryAdvance(Block<? super K> block) {
3699 if (block == null) throw new NullPointerException();
3700 Node<K,V> e;
3701 for (e = current; e != null; e = e.next) {
3702 K k; Object v;
3703 if (compareBounds(k = e.key) >= 0) {
3704 e = null;
3705 break;
3706 }
3707 if ((v = e.value) != null && v != e) {
3708 current = e.next;
3709 block.accept(k);
3710 return true;
3711 }
3712 }
3713 current = e;
3714 return false;
3715 }
3716 }
3717
3718 static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
3719 implements Spliterator<V> {
3720 ValueSpliterator(ConcurrentSkipListMap<K,V> m) { super(m); }
3721 ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3722 Node<K,V> origin, K fence, int est) {
3723 super(comparator, row, origin, fence, est);
3724 }
3725
3726 public ValueSpliterator<K,V> trySplit() {
3727 Node<K,V> e;
3728 Comparator<? super K> cmp = comparator;
3729 K f = fence;
3730 if ((e = current) != null) {
3731 for (Index<K,V> q = row; q != null; q = row = q.down) {
3732 Index<K,V> s; Node<K,V> n; K sk;
3733 est -= est >>> 2;
3734 if ((s = q.right) != null) {
3735 for (;;) {
3736 Node<K,V> b = s.node;
3737 if ((n = b.next) == null || n.value != null)
3738 break;
3739 n.helpDelete(b, n.next);
3740 }
3741 if (n != null && (sk = n.key) != null &&
3742 (f == null ||
3743 (cmp != null ? (cmp.compare(f, sk) > 0) :
3744 (((Comparable<? super K>)f).compareTo(sk) > 0)))) {
3745 current = n;
3746 Index<K,V> r = q.down;
3747 row = (s.right != null) ? s : s.down;
3748 return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
3749 }
3750 }
3751 }
3752 }
3753 return null;
3754 }
3755
3756 public void forEach(Block<? super V> block) {
3757 if (block == null) throw new NullPointerException();
3758 K f = fence;
3759 Comparator<? super K> cmp = comparator;
3760 Comparable<? super K> cf = (f != null && cmp == null) ?
3761 (Comparable<? super K>)f : null;
3762 Node<K,V> e = current;
3763 current = null;
3764 for (; e != null; e = e.next) {
3765 K k; Object v;
3766 if ((k = e.key) != null &&
3767 (cf != null ? (cf.compareTo(k) <= 0) :
3768 (f != null && cmp.compare(f, k) <= 0)))
3769 break;
3770 if ((v = e.value) != null && v != e)
3771 block.accept((V)v);
3772 }
3773 }
3774
3775 public boolean tryAdvance(Block<? super V> block) {
3776 if (block == null) throw new NullPointerException();
3777 boolean advanced = false;
3778 Node<K,V> e;
3779 for (e = current; e != null; e = e.next) {
3780 K k; Object v;
3781 if (compareBounds(k = e.key) >= 0) {
3782 e = null;
3783 break;
3784 }
3785 if ((v = e.value) != null && v != e) {
3786 current = e.next;
3787 block.accept((V)v);
3788 return true;
3789 }
3790 }
3791 current = e;
3792 return false;
3793 }
3794 }
3795
3796 static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
3797 implements Spliterator<Map.Entry<K,V>> {
3798 EntrySpliterator(ConcurrentSkipListMap<K,V> m) { super(m); }
3799 EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3800 Node<K,V> origin, K fence, int est) {
3801 super(comparator, row, origin, fence, est);
3802 }
3803
3804 public EntrySpliterator<K,V> trySplit() {
3805 Node<K,V> e;
3806 Comparator<? super K> cmp = comparator;
3807 K f = fence;
3808 if ((e = current) != null) {
3809 for (Index<K,V> q = row; q != null; q = row = q.down) {
3810 Index<K,V> s; Node<K,V> n; K sk;
3811 est -= est >>> 2;
3812 if ((s = q.right) != null) {
3813 for (;;) {
3814 Node<K,V> b = s.node;
3815 if ((n = b.next) == null || n.value != null)
3816 break;
3817 n.helpDelete(b, n.next);
3818 }
3819 if (n != null && (sk = n.key) != null &&
3820 (f == null ||
3821 (cmp != null ?
3822 (cmp.compare(f, sk) > 0) :
3823 (((Comparable<? super K>)f).compareTo(sk) > 0)))) {
3824 current = n;
3825 Index<K,V> r = q.down;
3826 row = (s.right != null) ? s : s.down;
3827 return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
3828 }
3829 }
3830 }
3831 }
3832 return null;
3833 }
3834
3835 public void forEach(Block<? super Map.Entry<K,V>> block) {
3836 if (block == null) throw new NullPointerException();
3837 K f = fence;
3838 Comparator<? super K> cmp = comparator;
3839 Comparable<? super K> cf = (f != null && cmp == null) ?
3840 (Comparable<? super K>)f : null;
3841 Node<K,V> e = current;
3842 current = null;
3843 for (; e != null; e = e.next) {
3844 K k; Object v;
3845 if ((k = e.key) != null &&
3846 (cf != null ?
3847 (cf.compareTo(k) <= 0) :
3848 (f != null && cmp.compare(f, k) <= 0)))
3849 break;
3850 if ((v = e.value) != null && v != e)
3851 block.accept
3852 (new AbstractMap.SimpleImmutableEntry<K,V>(k, (V)v));
3853 }
3854 }
3855
3856 public boolean tryAdvance(Block<? super Map.Entry<K,V>> block) {
3857 if (block == null) throw new NullPointerException();
3858 Node<K,V> e;
3859 for (e = current; e != null; e = e.next) {
3860 K k; Object v;
3861 if (compareBounds(k = e.key) >= 0) {
3862 e = null;
3863 break;
3864 }
3865 if ((v = e.value) != null && v != e) {
3866 current = e.next;
3867 block.accept
3868 (new AbstractMap.SimpleImmutableEntry<K,V>(k, (V)v));
3869 return true;
3870 }
3871 }
3872 current = e;
3873 return false;
3874 }
3875 }
3876
3877 // Unsafe mechanics
3878 private static final sun.misc.Unsafe UNSAFE;
3879 private static final long headOffset;
3880 private static final long SECONDARY;
3881 static {
3882 try {
3883 UNSAFE = sun.misc.Unsafe.getUnsafe();
3884 Class<?> k = ConcurrentSkipListMap.class;
3885 headOffset = UNSAFE.objectFieldOffset
3886 (k.getDeclaredField("head"));
3887 Class<?> tk = Thread.class;
3888 SECONDARY = UNSAFE.objectFieldOffset
3889 (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
3890
3891 } catch (Exception e) {
3892 throw new Error(e);
3893 }
3894 }
3895 }