ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.110
Committed: Mon Mar 18 18:34:07 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.109: +27 -27 lines
Log Message:
whitespace

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