ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.178
Committed: Fri Sep 29 14:39:55 2017 UTC (6 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.177: +1 -1 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
9 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.io.Serializable;
12 import java.util.AbstractCollection;
13 import java.util.AbstractMap;
14 import java.util.AbstractSet;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.NavigableSet;
23 import java.util.NoSuchElementException;
24 import java.util.Set;
25 import java.util.SortedMap;
26 import java.util.Spliterator;
27 import java.util.function.BiConsumer;
28 import java.util.function.BiFunction;
29 import java.util.function.Consumer;
30 import java.util.function.Function;
31 import java.util.function.Predicate;
32 import java.util.concurrent.atomic.LongAdder;
33
34 /**
35 * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
36 * The map is sorted according to the {@linkplain Comparable natural
37 * ordering} of its keys, or by a {@link Comparator} provided at map
38 * creation time, depending on which constructor is used.
39 *
40 * <p>This class implements a concurrent variant of <a
41 * href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a>
42 * providing expected average <i>log(n)</i> time cost for the
43 * {@code containsKey}, {@code get}, {@code put} and
44 * {@code remove} operations and their variants. Insertion, removal,
45 * update, and access operations safely execute concurrently by
46 * multiple threads.
47 *
48 * <p>Iterators and spliterators are
49 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
50 *
51 * <p>Ascending key ordered views and their iterators are faster than
52 * descending ones.
53 *
54 * <p>All {@code Map.Entry} pairs returned by methods in this class
55 * and its views represent snapshots of mappings at the time they were
56 * produced. They do <em>not</em> support the {@code Entry.setValue}
57 * method. (Note however that it is possible to change mappings in the
58 * associated map using {@code put}, {@code putIfAbsent}, or
59 * {@code replace}, depending on exactly which effect you need.)
60 *
61 * <p>Beware that bulk operations {@code putAll}, {@code equals},
62 * {@code toArray}, {@code containsValue}, and {@code clear} are
63 * <em>not</em> guaranteed to be performed atomically. For example, an
64 * iterator operating concurrently with a {@code putAll} operation
65 * might view only some of the added elements.
66 *
67 * <p>This class and its views and iterators implement all of the
68 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
69 * interfaces. Like most other concurrent collections, this class does
70 * <em>not</em> permit the use of {@code null} keys or values because some
71 * null return values cannot be reliably distinguished from the absence of
72 * elements.
73 *
74 * <p>This class is a member of the
75 * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
76 * Java Collections Framework</a>.
77 *
78 * @author Doug Lea
79 * @param <K> the type of keys maintained by this map
80 * @param <V> the type of mapped values
81 * @since 1.6
82 */
83 public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
84 implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable {
85 /*
86 * This class implements a tree-like two-dimensionally linked skip
87 * list in which the index levels are represented in separate
88 * nodes from the base nodes holding data. There are two reasons
89 * for taking this approach instead of the usual array-based
90 * structure: 1) Array based implementations seem to encounter
91 * more complexity and overhead 2) We can use cheaper algorithms
92 * for the heavily-traversed index lists than can be used for the
93 * base lists. Here's a picture of some of the basics for a
94 * possible list with 2 levels of index:
95 *
96 * Head nodes Index nodes
97 * +-+ right +-+ +-+
98 * |2|---------------->| |--------------------->| |->null
99 * +-+ +-+ +-+
100 * | down | |
101 * v v v
102 * +-+ +-+ +-+ +-+ +-+ +-+
103 * |1|----------->| |->| |------>| |----------->| |------>| |->null
104 * +-+ +-+ +-+ +-+ +-+ +-+
105 * v | | | | |
106 * Nodes next v v v v v
107 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
108 * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
109 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
110 *
111 * The base lists use a variant of the HM linked ordered set
112 * algorithm. See Tim Harris, "A pragmatic implementation of
113 * non-blocking linked lists"
114 * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
115 * Michael "High Performance Dynamic Lock-Free Hash Tables and
116 * List-Based Sets"
117 * http://www.research.ibm.com/people/m/michael/pubs.htm. The
118 * basic idea in these lists is to mark the "next" pointers of
119 * deleted nodes when deleting to avoid conflicts with concurrent
120 * insertions, and when traversing to keep track of triples
121 * (predecessor, node, successor) in order to detect when and how
122 * to unlink these deleted nodes.
123 *
124 * Rather than using mark-bits to mark list deletions (which can
125 * be slow and space-intensive using AtomicMarkedReference), nodes
126 * use direct CAS'able next pointers. On deletion, instead of
127 * marking a pointer, they splice in another node that can be
128 * thought of as standing for a marked pointer (see method
129 * unlinkNode). Using plain nodes acts roughly like "boxed"
130 * implementations of marked pointers, but uses new nodes only
131 * when nodes are deleted, not for every link. This requires less
132 * space and supports faster traversal. Even if marked references
133 * were better supported by JVMs, traversal using this technique
134 * might still be faster because any search need only read ahead
135 * one more node than otherwise required (to check for trailing
136 * marker) rather than unmasking mark bits or whatever on each
137 * read.
138 *
139 * This approach maintains the essential property needed in the HM
140 * algorithm of changing the next-pointer of a deleted node so
141 * that any other CAS of it will fail, but implements the idea by
142 * changing the pointer to point to a different node (with
143 * otherwise illegal null fields), not by marking it. While it
144 * would be possible to further squeeze space by defining marker
145 * nodes not to have key/value fields, it isn't worth the extra
146 * type-testing overhead. The deletion markers are rarely
147 * encountered during traversal, are easily detected via null
148 * checks that are needed anyway, and are normally quickly garbage
149 * collected. (Note that this technique would not work well in
150 * systems without garbage collection.)
151 *
152 * In addition to using deletion markers, the lists also use
153 * nullness of value fields to indicate deletion, in a style
154 * similar to typical lazy-deletion schemes. If a node's value is
155 * null, then it is considered logically deleted and ignored even
156 * though it is still reachable.
157 *
158 * Here's the sequence of events for a deletion of node n with
159 * predecessor b and successor f, initially:
160 *
161 * +------+ +------+ +------+
162 * ... | b |------>| n |----->| f | ...
163 * +------+ +------+ +------+
164 *
165 * 1. CAS n's value field from non-null to null.
166 * Traversals encountering a node with null value ignore it.
167 * However, ongoing insertions and deletions might still modify
168 * n's next pointer.
169 *
170 * 2. CAS n's next pointer to point to a new marker node.
171 * From this point on, no other nodes can be appended to n.
172 * which avoids deletion errors in CAS-based linked lists.
173 *
174 * +------+ +------+ +------+ +------+
175 * ... | b |------>| n |----->|marker|------>| f | ...
176 * +------+ +------+ +------+ +------+
177 *
178 * 3. CAS b's next pointer over both n and its marker.
179 * From this point on, no new traversals will encounter n,
180 * and it can eventually be GCed.
181 * +------+ +------+
182 * ... | b |----------------------------------->| f | ...
183 * +------+ +------+
184 *
185 * A failure at step 1 leads to simple retry due to a lost race
186 * with another operation. Steps 2-3 can fail because some other
187 * thread noticed during a traversal a node with null value and
188 * helped out by marking and/or unlinking. This helping-out
189 * ensures that no thread can become stuck waiting for progress of
190 * the deleting thread.
191 *
192 * Skip lists add indexing to this scheme, so that the base-level
193 * traversals start close to the locations being found, inserted
194 * or deleted -- usually base level traversals only traverse a few
195 * nodes. This doesn't change the basic algorithm except for the
196 * need to make sure base traversals start at predecessors (here,
197 * b) that are not (structurally) deleted, otherwise retrying
198 * after processing the deletion.
199 *
200 * Index levels are maintained using CAS to link and unlink
201 * successors ("right" fields). Races are allowed in index-list
202 * operations that can (rarely) fail to link in a new index node.
203 * (We can't do this of course for data nodes.) However, even
204 * when this happens, the index lists correctly guide search.
205 * This can impact performance, but since skip lists are
206 * probabilistic anyway, the net result is that under contention,
207 * the effective "p" value may be lower than its nominal value.
208 *
209 * Index insertion and deletion sometimes require a separate
210 * traversal pass occurring after the base-level action, to add or
211 * remove index nodes. This adds to single-threaded overhead, but
212 * improves contended multithreaded performance by narrowing
213 * interference windows, and allows deletion to ensure that all
214 * index nodes will be made unreachable upon return from a public
215 * remove operation, thus avoiding unwanted garbage retention.
216 *
217 * Indexing uses skip list parameters that maintain good search
218 * performance while using sparser-than-usual indices: The
219 * hardwired parameters k=1, p=0.5 (see method doPut) mean that
220 * about one-quarter of the nodes have indices. Of those that do,
221 * half have one level, a quarter have two, and so on (see Pugh's
222 * Skip List Cookbook, sec 3.4), up to a maximum of 62 levels
223 * (appropriate for up to 2^63 elements). The expected total
224 * space requirement for a map is slightly less than for the
225 * current implementation of java.util.TreeMap.
226 *
227 * Changing the level of the index (i.e, the height of the
228 * tree-like structure) also uses CAS. Creation of an index with
229 * height greater than the current level adds a level to the head
230 * index by CAS'ing on a new top-most head. To maintain good
231 * performance after a lot of removals, deletion methods
232 * heuristically try to reduce the height if the topmost levels
233 * appear to be empty. This may encounter races in which it is
234 * possible (but rare) to reduce and "lose" a level just as it is
235 * about to contain an index (that will then never be
236 * encountered). This does no structural harm, and in practice
237 * appears to be a better option than allowing unrestrained growth
238 * of levels.
239 *
240 * This class provides concurrent-reader-style memory consistency,
241 * ensuring that read-only methods report status and/or values no
242 * staler than those holding at method entry. This is done by
243 * performing all publication and structural updates using
244 * (volatile) CAS, placing an acquireFence in a few access
245 * methods, and ensuring that linked objects are transitively
246 * acquired via dependent reads (normally once) unless performing
247 * a volatile-mode CAS operation (that also acts as an acquire and
248 * release). This form of fence-hoisting is similar to RCU and
249 * related techniques (see McKenney's online book
250 * https://www.kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html)
251 * It minimizes overhead that may otherwise occur when using so
252 * many volatile-mode reads. Using explicit acquireFences is
253 * logistically easier than targeting particular fields to be read
254 * in acquire mode: fences are just hoisted up as far as possible,
255 * to the entry points or loop headers of a few methods. A
256 * potential disadvantage is that these few remaining fences are
257 * not easily optimized away by compilers under exclusively
258 * single-thread use. It requires some care to avoid volatile
259 * mode reads of other fields. (Note that the memory semantics of
260 * a reference dependently read in plain mode exactly once are
261 * equivalent to those for atomic opaque mode.) Iterators and
262 * other traversals encounter each node and value exactly once.
263 * Other operations locate an element (or position to insert an
264 * element) via a sequence of dereferences. This search is broken
265 * into two parts. Method findPredecessor (and its specialized
266 * embeddings) searches index nodes only, returning a base-level
267 * predecessor of the key. Callers carry out the base-level
268 * search, restarting if encountering a marker preventing link
269 * modification. In some cases, it is possible to encounter a
270 * node multiple times while descending levels. For mutative
271 * operations, the reported value is validated using CAS (else
272 * retrying), preserving linearizability with respect to each
273 * other. Others may return any (non-null) value holding in the
274 * course of the method call. (Search-based methods also include
275 * some useless-looking explicit null checks designed to allow
276 * more fields to be nulled out upon removal, to reduce floating
277 * garbage, but which is not currently done, pending discovery of
278 * a way to do this with less impact on other operations.)
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 * For explanation of algorithms sharing at least a couple of
286 * features with this one, see Mikhail Fomitchev's thesis
287 * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
288 * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
289 * thesis (http://www.cs.chalmers.se/~phs/).
290 *
291 * Notation guide for local variables
292 * Node: b, n, f, p for predecessor, node, successor, aux
293 * Index: q, r, d for index node, right, down.
294 * Head: h
295 * Keys: k, key
296 * Values: v, value
297 * Comparisons: c
298 */
299
300 private static final long serialVersionUID = -8627078645895051609L;
301
302 /**
303 * The comparator used to maintain order in this map, or null if
304 * using natural ordering. (Non-private to simplify access in
305 * nested classes.)
306 * @serial
307 */
308 final Comparator<? super K> comparator;
309
310 /** Lazily initialized topmost index of the skiplist. */
311 private transient Index<K,V> head;
312 /** Lazily initialized element count */
313 private transient LongAdder adder;
314 /** Lazily initialized key set */
315 private transient KeySet<K,V> keySet;
316 /** Lazily initialized values collection */
317 private transient Values<K,V> values;
318 /** Lazily initialized entry set */
319 private transient EntrySet<K,V> entrySet;
320 /** Lazily initialized descending map */
321 private transient SubMap<K,V> descendingMap;
322
323 /**
324 * Nodes hold keys and values, and are singly linked in sorted
325 * order, possibly with some intervening marker nodes. The list is
326 * headed by a header node accessible as head.node. Headers and
327 * marker nodes have null keys. The val field (but currently not
328 * the key field) is nulled out upon deletion.
329 */
330 static final class Node<K,V> {
331 final K key; // currently, never detached
332 V val;
333 Node<K,V> next;
334 Node(K key, V value, Node<K,V> next) {
335 this.key = key;
336 this.val = value;
337 this.next = next;
338 }
339 }
340
341 /**
342 * Index nodes represent the levels of the skip list.
343 */
344 static final class Index<K,V> {
345 final Node<K,V> node; // currently, never detached
346 final Index<K,V> down;
347 Index<K,V> right;
348 Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
349 this.node = node;
350 this.down = down;
351 this.right = right;
352 }
353 }
354
355 /* ---------------- Utilities -------------- */
356
357 /**
358 * Compares using comparator or natural ordering if null.
359 * Called only by methods that have performed required type checks.
360 */
361 @SuppressWarnings({"unchecked", "rawtypes"})
362 static int cpr(Comparator c, Object x, Object y) {
363 return (c != null) ? c.compare(x, y) : ((Comparable)x).compareTo(y);
364 }
365
366 /**
367 * Returns the header for base node list, or null if uninitialized
368 */
369 final Node<K,V> baseHead() {
370 Index<K,V> h;
371 VarHandle.acquireFence();
372 return ((h = head) == null) ? null : h.node;
373 }
374
375 /**
376 * Tries to unlink deleted node n from predecessor b (if both
377 * exist), by first splicing in a marker if not already present.
378 * Upon return, node n is sure to be unlinked from b, possibly
379 * via the actions of some other thread.
380 *
381 * @param b if nonnull, predecessor
382 * @param n if nonnull, node known to be deleted
383 */
384 static <K,V> void unlinkNode(Node<K,V> b, Node<K,V> n) {
385 if (b != null && n != null) {
386 Node<K,V> f, p;
387 for (;;) {
388 if ((f = n.next) != null && f.key == null) {
389 p = f.next; // already marked
390 break;
391 }
392 else if (NEXT.compareAndSet(n, f,
393 new Node<K,V>(null, null, f))) {
394 p = f; // add marker
395 break;
396 }
397 }
398 NEXT.compareAndSet(b, n, p);
399 }
400 }
401
402 /**
403 * Adds to element count, initializing adder if necessary
404 *
405 * @param c count to add
406 */
407 private void addCount(long c) {
408 LongAdder a;
409 do {} while ((a = adder) == null &&
410 !ADDER.compareAndSet(this, null, a = new LongAdder()));
411 a.add(c);
412 }
413
414 /**
415 * Returns element count, initializing adder if necessary.
416 */
417 final long getAdderCount() {
418 LongAdder a; long c;
419 do {} while ((a = adder) == null &&
420 !ADDER.compareAndSet(this, null, a = new LongAdder()));
421 return ((c = a.sum()) <= 0L) ? 0L : c; // ignore transient negatives
422 }
423
424 /* ---------------- Traversal -------------- */
425
426 /**
427 * Returns an index node with key strictly less than given key.
428 * Also unlinks indexes to deleted nodes found along the way.
429 * Callers rely on this side-effect of clearing indices to deleted
430 * nodes.
431 *
432 * @param key if nonnull the key
433 * @return a predecessor node of key, or null if uninitialized or null key
434 */
435 private Node<K,V> findPredecessor(Object key, Comparator<? super K> cmp) {
436 Index<K,V> q;
437 VarHandle.acquireFence();
438 if ((q = head) == null || key == null)
439 return null;
440 else {
441 for (Index<K,V> r, d;;) {
442 while ((r = q.right) != null) {
443 Node<K,V> p; K k;
444 if ((p = r.node) == null || (k = p.key) == null ||
445 p.val == null) // unlink index to deleted node
446 RIGHT.compareAndSet(q, r, r.right);
447 else if (cpr(cmp, key, k) > 0)
448 q = r;
449 else
450 break;
451 }
452 if ((d = q.down) != null)
453 q = d;
454 else
455 return q.node;
456 }
457 }
458 }
459
460 /**
461 * Returns node holding key or null if no such, clearing out any
462 * deleted nodes seen along the way. Repeatedly traverses at
463 * base-level looking for key starting at predecessor returned
464 * from findPredecessor, processing base-level deletions as
465 * encountered. Restarts occur, at traversal step encountering
466 * node n, if n's key field is null, indicating it is a marker, so
467 * its predecessor is deleted before continuing, which we help do
468 * by re-finding a valid predecessor. The traversal loops in
469 * doPut, doRemove, and findNear all include the same checks.
470 *
471 * @param key the key
472 * @return node holding key, or null if no such
473 */
474 private Node<K,V> findNode(Object key) {
475 if (key == null)
476 throw new NullPointerException(); // don't postpone errors
477 Comparator<? super K> cmp = comparator;
478 Node<K,V> b;
479 outer: while ((b = findPredecessor(key, cmp)) != null) {
480 for (;;) {
481 Node<K,V> n; K k; V v; int c;
482 if ((n = b.next) == null)
483 break outer; // empty
484 else if ((k = n.key) == null)
485 break; // b is deleted
486 else if ((v = n.val) == null)
487 unlinkNode(b, n); // n is deleted
488 else if ((c = cpr(cmp, key, k)) > 0)
489 b = n;
490 else if (c == 0)
491 return n;
492 else
493 break outer;
494 }
495 }
496 return null;
497 }
498
499 /**
500 * Gets value for key. Same idea as findNode, except skips over
501 * deletions and markers, and returns first encountered value to
502 * avoid possibly inconsistent rereads.
503 *
504 * @param key the key
505 * @return the value, or null if absent
506 */
507 private V doGet(Object key) {
508 Index<K,V> q;
509 VarHandle.acquireFence();
510 if (key == null)
511 throw new NullPointerException();
512 Comparator<? super K> cmp = comparator;
513 V result = null;
514 if ((q = head) != null) {
515 outer: for (Index<K,V> r, d;;) {
516 while ((r = q.right) != null) {
517 Node<K,V> p; K k; V v; int c;
518 if ((p = r.node) == null || (k = p.key) == null ||
519 (v = p.val) == null)
520 RIGHT.compareAndSet(q, r, r.right);
521 else if ((c = cpr(cmp, key, k)) > 0)
522 q = r;
523 else if (c == 0) {
524 result = v;
525 break outer;
526 }
527 else
528 break;
529 }
530 if ((d = q.down) != null)
531 q = d;
532 else {
533 Node<K,V> b, n;
534 if ((b = q.node) != null) {
535 while ((n = b.next) != null) {
536 V v; int c;
537 K k = n.key;
538 if ((v = n.val) == null || k == null ||
539 (c = cpr(cmp, key, k)) > 0)
540 b = n;
541 else {
542 if (c == 0)
543 result = v;
544 break;
545 }
546 }
547 }
548 break;
549 }
550 }
551 }
552 return result;
553 }
554
555 /* ---------------- Insertion -------------- */
556
557 /**
558 * Main insertion method. Adds element if not present, or
559 * replaces value if present and onlyIfAbsent is false.
560 *
561 * @param key the key
562 * @param value the value that must be associated with key
563 * @param onlyIfAbsent if should not insert if already present
564 * @return the old value, or null if newly inserted
565 */
566 private V doPut(K key, V value, boolean onlyIfAbsent) {
567 if (key == null)
568 throw new NullPointerException();
569 Comparator<? super K> cmp = comparator;
570 for (;;) {
571 Index<K,V> h; Node<K,V> b;
572 VarHandle.acquireFence();
573 int levels = 0; // number of levels descended
574 if ((h = head) == null) { // try to initialize
575 Node<K,V> base = new Node<K,V>(null, null, null);
576 h = new Index<K,V>(base, null, null);
577 b = (HEAD.compareAndSet(this, null, h)) ? base : null;
578 }
579 else {
580 for (Index<K,V> q = h, r, d;;) { // count while descending
581 while ((r = q.right) != null) {
582 Node<K,V> p; K k;
583 if ((p = r.node) == null || (k = p.key) == null ||
584 p.val == null)
585 RIGHT.compareAndSet(q, r, r.right);
586 else if (cpr(cmp, key, k) > 0)
587 q = r;
588 else
589 break;
590 }
591 if ((d = q.down) != null) {
592 ++levels;
593 q = d;
594 }
595 else {
596 b = q.node;
597 break;
598 }
599 }
600 }
601 if (b != null) {
602 Node<K,V> z = null; // new node, if inserted
603 for (;;) { // find insertion point
604 Node<K,V> n, p; K k; V v; int c;
605 if ((n = b.next) == null) {
606 if (b.key == null) // if empty, type check key now
607 cpr(cmp, key, key);
608 c = -1;
609 }
610 else if ((k = n.key) == null)
611 break; // can't append; restart
612 else if ((v = n.val) == null) {
613 unlinkNode(b, n);
614 c = 1;
615 }
616 else if ((c = cpr(cmp, key, k)) > 0)
617 b = n;
618 else if (c == 0 &&
619 (onlyIfAbsent || VAL.compareAndSet(n, v, value)))
620 return v;
621
622 if (c < 0 &&
623 NEXT.compareAndSet(b, n,
624 p = new Node<K,V>(key, value, n))) {
625 z = p;
626 break;
627 }
628 }
629
630 if (z != null) {
631 int lr = ThreadLocalRandom.nextSecondarySeed();
632 if ((lr & 0x3) == 0) { // add indices with 1/4 prob
633 int hr = ThreadLocalRandom.nextSecondarySeed();
634 long rnd = ((long)hr << 32) | ((long)lr & 0xffffffffL);
635 int skips = levels; // levels to descend before add
636 Index<K,V> x = null;
637 for (;;) { // create at most 62 indices
638 x = new Index<K,V>(z, x, null);
639 if (rnd >= 0L || --skips < 0)
640 break;
641 else
642 rnd <<= 1;
643 }
644 if (addIndices(h, skips, x, cmp) && skips < 0 &&
645 head == h) { // try to add new level
646 Index<K,V> hx = new Index<K,V>(z, x, null);
647 Index<K,V> nh = new Index<K,V>(h.node, h, hx);
648 HEAD.compareAndSet(this, h, nh);
649 }
650 if (z.val == null) // deleted while adding indices
651 findPredecessor(key, cmp); // clean
652 }
653 addCount(1L);
654 return null;
655 }
656 }
657 }
658 }
659
660 /**
661 * Add indices after an insertion. Descends iteratively to the
662 * highest level of insertion, then recursively, to chain index
663 * nodes to lower ones. Returns null on (staleness) failure,
664 * disabling higher-level insertions. Recursion depths are
665 * exponentially less probable.
666 *
667 * @param q starting index for current level
668 * @param skips levels to skip before inserting
669 * @param x index for this insertion
670 * @param cmp comparator
671 */
672 static <K,V> boolean addIndices(Index<K,V> q, int skips, Index<K,V> x,
673 Comparator<? super K> cmp) {
674 Node<K,V> z; K key;
675 if (x != null && (z = x.node) != null && (key = z.key) != null &&
676 q != null) { // hoist checks
677 boolean retrying = false;
678 for (;;) { // find splice point
679 Index<K,V> r, d; int c;
680 if ((r = q.right) != null) {
681 Node<K,V> p; K k;
682 if ((p = r.node) == null || (k = p.key) == null ||
683 p.val == null) {
684 RIGHT.compareAndSet(q, r, r.right);
685 c = 0;
686 }
687 else if ((c = cpr(cmp, key, k)) > 0)
688 q = r;
689 else if (c == 0)
690 break; // stale
691 }
692 else
693 c = -1;
694
695 if (c < 0) {
696 if ((d = q.down) != null && skips > 0) {
697 --skips;
698 q = d;
699 }
700 else if (d != null && !retrying &&
701 !addIndices(d, 0, x.down, cmp))
702 break;
703 else {
704 x.right = r;
705 if (RIGHT.compareAndSet(q, r, x))
706 return true;
707 else
708 retrying = true; // re-find splice point
709 }
710 }
711 }
712 }
713 return false;
714 }
715
716 /* ---------------- Deletion -------------- */
717
718 /**
719 * Main deletion method. Locates node, nulls value, appends a
720 * deletion marker, unlinks predecessor, removes associated index
721 * nodes, and possibly reduces head index level.
722 *
723 * @param key the key
724 * @param value if non-null, the value that must be
725 * associated with key
726 * @return the node, or null if not found
727 */
728 final V doRemove(Object key, Object value) {
729 if (key == null)
730 throw new NullPointerException();
731 Comparator<? super K> cmp = comparator;
732 V result = null;
733 Node<K,V> b;
734 outer: while ((b = findPredecessor(key, cmp)) != null &&
735 result == null) {
736 for (;;) {
737 Node<K,V> n; K k; V v; int c;
738 if ((n = b.next) == null)
739 break outer;
740 else if ((k = n.key) == null)
741 break;
742 else if ((v = n.val) == null)
743 unlinkNode(b, n);
744 else if ((c = cpr(cmp, key, k)) > 0)
745 b = n;
746 else if (c < 0)
747 break outer;
748 else if (value != null && !value.equals(v))
749 break outer;
750 else if (VAL.compareAndSet(n, v, null)) {
751 result = v;
752 unlinkNode(b, n);
753 break; // loop to clean up
754 }
755 }
756 }
757 if (result != null) {
758 tryReduceLevel();
759 addCount(-1L);
760 }
761 return result;
762 }
763
764 /**
765 * Possibly reduce head level if it has no nodes. This method can
766 * (rarely) make mistakes, in which case levels can disappear even
767 * though they are about to contain index nodes. This impacts
768 * performance, not correctness. To minimize mistakes as well as
769 * to reduce hysteresis, the level is reduced by one only if the
770 * topmost three levels look empty. Also, if the removed level
771 * looks non-empty after CAS, we try to change it back quick
772 * before anyone notices our mistake! (This trick works pretty
773 * well because this method will practically never make mistakes
774 * unless current thread stalls immediately before first CAS, in
775 * which case it is very unlikely to stall again immediately
776 * afterwards, so will recover.)
777 *
778 * We put up with all this rather than just let levels grow
779 * because otherwise, even a small map that has undergone a large
780 * number of insertions and removals will have a lot of levels,
781 * slowing down access more than would an occasional unwanted
782 * reduction.
783 */
784 private void tryReduceLevel() {
785 Index<K,V> h, d, e;
786 if ((h = head) != null && h.right == null &&
787 (d = h.down) != null && d.right == null &&
788 (e = d.down) != null && e.right == null &&
789 HEAD.compareAndSet(this, h, d) &&
790 h.right != null) // recheck
791 HEAD.compareAndSet(this, d, h); // try to backout
792 }
793
794 /* ---------------- Finding and removing first element -------------- */
795
796 /**
797 * Gets first valid node, unlinking deleted nodes if encountered.
798 * @return first node or null if empty
799 */
800 final Node<K,V> findFirst() {
801 Node<K,V> b, n;
802 if ((b = baseHead()) != null) {
803 while ((n = b.next) != null) {
804 if (n.val == null)
805 unlinkNode(b, n);
806 else
807 return n;
808 }
809 }
810 return null;
811 }
812
813 /**
814 * Entry snapshot version of findFirst
815 */
816 final AbstractMap.SimpleImmutableEntry<K,V> findFirstEntry() {
817 Node<K,V> b, n; V v;
818 if ((b = baseHead()) != null) {
819 while ((n = b.next) != null) {
820 if ((v = n.val) == null)
821 unlinkNode(b, n);
822 else
823 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
824 }
825 }
826 return null;
827 }
828
829 /**
830 * Removes first entry; returns its snapshot.
831 * @return null if empty, else snapshot of first entry
832 */
833 private AbstractMap.SimpleImmutableEntry<K,V> doRemoveFirstEntry() {
834 Node<K,V> b, n; V v;
835 if ((b = baseHead()) != null) {
836 while ((n = b.next) != null) {
837 if ((v = n.val) == null || VAL.compareAndSet(n, v, null)) {
838 K k = n.key;
839 unlinkNode(b, n);
840 if (v != null) {
841 tryReduceLevel();
842 findPredecessor(k, comparator); // clean index
843 addCount(-1L);
844 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
845 }
846 }
847 }
848 }
849 return null;
850 }
851
852 /* ---------------- Finding and removing last element -------------- */
853
854 /**
855 * Specialized version of find to get last valid node.
856 * @return last node or null if empty
857 */
858 final Node<K,V> findLast() {
859 outer: for (;;) {
860 Index<K,V> q; Node<K,V> b;
861 VarHandle.acquireFence();
862 if ((q = head) == null)
863 break;
864 for (Index<K,V> r, d;;) {
865 while ((r = q.right) != null) {
866 Node<K,V> p;
867 if ((p = r.node) == null || p.val == null)
868 RIGHT.compareAndSet(q, r, r.right);
869 else
870 q = r;
871 }
872 if ((d = q.down) != null)
873 q = d;
874 else {
875 b = q.node;
876 break;
877 }
878 }
879 if (b != null) {
880 for (;;) {
881 Node<K,V> n;
882 if ((n = b.next) == null) {
883 if (b.key == null) // empty
884 break outer;
885 else
886 return b;
887 }
888 else if (n.key == null)
889 break;
890 else if (n.val == null)
891 unlinkNode(b, n);
892 else
893 b = n;
894 }
895 }
896 }
897 return null;
898 }
899
900 /**
901 * Entry version of findLast
902 * @return Entry for last node or null if empty
903 */
904 final AbstractMap.SimpleImmutableEntry<K,V> findLastEntry() {
905 for (;;) {
906 Node<K,V> n; V v;
907 if ((n = findLast()) == null)
908 return null;
909 if ((v = n.val) != null)
910 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
911 }
912 }
913
914 /**
915 * Removes last entry; returns its snapshot.
916 * Specialized variant of doRemove.
917 * @return null if empty, else snapshot of last entry
918 */
919 private Map.Entry<K,V> doRemoveLastEntry() {
920 outer: for (;;) {
921 Index<K,V> q; Node<K,V> b;
922 VarHandle.acquireFence();
923 if ((q = head) == null)
924 break;
925 for (;;) {
926 Index<K,V> d, r; Node<K,V> p;
927 while ((r = q.right) != null) {
928 if ((p = r.node) == null || p.val == null)
929 RIGHT.compareAndSet(q, r, r.right);
930 else if (p.next != null)
931 q = r; // continue only if a successor
932 else
933 break;
934 }
935 if ((d = q.down) != null)
936 q = d;
937 else {
938 b = q.node;
939 break;
940 }
941 }
942 if (b != null) {
943 for (;;) {
944 Node<K,V> n; K k; V v;
945 if ((n = b.next) == null) {
946 if (b.key == null) // empty
947 break outer;
948 else
949 break; // retry
950 }
951 else if ((k = n.key) == null)
952 break;
953 else if ((v = n.val) == null)
954 unlinkNode(b, n);
955 else if (n.next != null)
956 b = n;
957 else if (VAL.compareAndSet(n, v, null)) {
958 unlinkNode(b, n);
959 tryReduceLevel();
960 findPredecessor(k, comparator); // clean index
961 addCount(-1L);
962 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
963 }
964 }
965 }
966 }
967 return null;
968 }
969
970 /* ---------------- Relational operations -------------- */
971
972 // Control values OR'ed as arguments to findNear
973
974 private static final int EQ = 1;
975 private static final int LT = 2;
976 private static final int GT = 0; // Actually checked as !LT
977
978 /**
979 * Utility for ceiling, floor, lower, higher methods.
980 * @param key the key
981 * @param rel the relation -- OR'ed combination of EQ, LT, GT
982 * @return nearest node fitting relation, or null if no such
983 */
984 final Node<K,V> findNear(K key, int rel, Comparator<? super K> cmp) {
985 if (key == null)
986 throw new NullPointerException();
987 Node<K,V> result;
988 outer: for (Node<K,V> b;;) {
989 if ((b = findPredecessor(key, cmp)) == null) {
990 result = null;
991 break; // empty
992 }
993 for (;;) {
994 Node<K,V> n; K k; int c;
995 if ((n = b.next) == null) {
996 result = ((rel & LT) != 0 && b.key != null) ? b : null;
997 break outer;
998 }
999 else if ((k = n.key) == null)
1000 break;
1001 else if (n.val == null)
1002 unlinkNode(b, n);
1003 else if (((c = cpr(cmp, key, k)) == 0 && (rel & EQ) != 0) ||
1004 (c < 0 && (rel & LT) == 0)) {
1005 result = n;
1006 break outer;
1007 }
1008 else if (c <= 0 && (rel & LT) != 0) {
1009 result = (b.key != null) ? b : null;
1010 break outer;
1011 }
1012 else
1013 b = n;
1014 }
1015 }
1016 return result;
1017 }
1018
1019 /**
1020 * Variant of findNear returning SimpleImmutableEntry
1021 * @param key the key
1022 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1023 * @return Entry fitting relation, or null if no such
1024 */
1025 final AbstractMap.SimpleImmutableEntry<K,V> findNearEntry(K key, int rel,
1026 Comparator<? super K> cmp) {
1027 for (;;) {
1028 Node<K,V> n; V v;
1029 if ((n = findNear(key, rel, cmp)) == null)
1030 return null;
1031 if ((v = n.val) != null)
1032 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
1033 }
1034 }
1035
1036 /* ---------------- Constructors -------------- */
1037
1038 /**
1039 * Constructs a new, empty map, sorted according to the
1040 * {@linkplain Comparable natural ordering} of the keys.
1041 */
1042 public ConcurrentSkipListMap() {
1043 this.comparator = null;
1044 }
1045
1046 /**
1047 * Constructs a new, empty map, sorted according to the specified
1048 * comparator.
1049 *
1050 * @param comparator the comparator that will be used to order this map.
1051 * If {@code null}, the {@linkplain Comparable natural
1052 * ordering} of the keys will be used.
1053 */
1054 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1055 this.comparator = comparator;
1056 }
1057
1058 /**
1059 * Constructs a new map containing the same mappings as the given map,
1060 * sorted according to the {@linkplain Comparable natural ordering} of
1061 * the keys.
1062 *
1063 * @param m the map whose mappings are to be placed in this map
1064 * @throws ClassCastException if the keys in {@code m} are not
1065 * {@link Comparable}, or are not mutually comparable
1066 * @throws NullPointerException if the specified map or any of its keys
1067 * or values are null
1068 */
1069 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1070 this.comparator = null;
1071 putAll(m);
1072 }
1073
1074 /**
1075 * Constructs a new map containing the same mappings and using the
1076 * same ordering as the specified sorted map.
1077 *
1078 * @param m the sorted map whose mappings are to be placed in this
1079 * map, and whose comparator is to be used to sort this map
1080 * @throws NullPointerException if the specified sorted map or any of
1081 * its keys or values are null
1082 */
1083 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1084 this.comparator = m.comparator();
1085 buildFromSorted(m); // initializes transients
1086 }
1087
1088 /**
1089 * Returns a shallow copy of this {@code ConcurrentSkipListMap}
1090 * instance. (The keys and values themselves are not cloned.)
1091 *
1092 * @return a shallow copy of this map
1093 */
1094 public ConcurrentSkipListMap<K,V> clone() {
1095 try {
1096 @SuppressWarnings("unchecked")
1097 ConcurrentSkipListMap<K,V> clone =
1098 (ConcurrentSkipListMap<K,V>) super.clone();
1099 clone.keySet = null;
1100 clone.entrySet = null;
1101 clone.values = null;
1102 clone.descendingMap = null;
1103 clone.buildFromSorted(this);
1104 return clone;
1105 } catch (CloneNotSupportedException e) {
1106 throw new InternalError();
1107 }
1108 }
1109
1110 /**
1111 * Streamlined bulk insertion to initialize from elements of
1112 * given sorted map. Call only from constructor or clone
1113 * method.
1114 */
1115 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1116 if (map == null)
1117 throw new NullPointerException();
1118 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1119 map.entrySet().iterator();
1120
1121 /*
1122 * Add equally spaced indices at log intervals, using the bits
1123 * of count during insertion. The maximum possible resulting
1124 * level is less than the number of bits in a long (64). The
1125 * preds array tracks the current rightmost node at each
1126 * level.
1127 */
1128 @SuppressWarnings("unchecked")
1129 Index<K,V>[] preds = (Index<K,V>[])new Index<?,?>[64];
1130 Node<K,V> bp = new Node<K,V>(null, null, null);
1131 Index<K,V> h = preds[0] = new Index<K,V>(bp, null, null);
1132 long count = 0;
1133
1134 while (it.hasNext()) {
1135 Map.Entry<? extends K, ? extends V> e = it.next();
1136 K k = e.getKey();
1137 V v = e.getValue();
1138 if (k == null || v == null)
1139 throw new NullPointerException();
1140 Node<K,V> z = new Node<K,V>(k, v, null);
1141 bp = bp.next = z;
1142 if ((++count & 3L) == 0L) {
1143 long m = count >>> 2;
1144 int i = 0;
1145 Index<K,V> idx = null, q;
1146 do {
1147 idx = new Index<K,V>(z, idx, null);
1148 if ((q = preds[i]) == null)
1149 preds[i] = h = new Index<K,V>(h.node, h, idx);
1150 else
1151 preds[i] = q.right = idx;
1152 } while (++i < preds.length && ((m >>>= 1) & 1L) != 0L);
1153 }
1154 }
1155 if (count != 0L) {
1156 VarHandle.releaseFence(); // emulate volatile stores
1157 addCount(count);
1158 head = h;
1159 VarHandle.fullFence();
1160 }
1161 }
1162
1163 /* ---------------- Serialization -------------- */
1164
1165 /**
1166 * Saves this map to a stream (that is, serializes it).
1167 *
1168 * @param s the stream
1169 * @throws java.io.IOException if an I/O error occurs
1170 * @serialData The key (Object) and value (Object) for each
1171 * key-value mapping represented by the map, followed by
1172 * {@code null}. The key-value mappings are emitted in key-order
1173 * (as determined by the Comparator, or by the keys' natural
1174 * ordering if no Comparator).
1175 */
1176 private void writeObject(java.io.ObjectOutputStream s)
1177 throws java.io.IOException {
1178 // Write out the Comparator and any hidden stuff
1179 s.defaultWriteObject();
1180
1181 // Write out keys and values (alternating)
1182 Node<K,V> b, n; V v;
1183 if ((b = baseHead()) != null) {
1184 while ((n = b.next) != null) {
1185 if ((v = n.val) != null) {
1186 s.writeObject(n.key);
1187 s.writeObject(v);
1188 }
1189 b = n;
1190 }
1191 }
1192 s.writeObject(null);
1193 }
1194
1195 /**
1196 * Reconstitutes this map from a stream (that is, deserializes it).
1197 * @param s the stream
1198 * @throws ClassNotFoundException if the class of a serialized object
1199 * could not be found
1200 * @throws java.io.IOException if an I/O error occurs
1201 */
1202 @SuppressWarnings("unchecked")
1203 private void readObject(final java.io.ObjectInputStream s)
1204 throws java.io.IOException, ClassNotFoundException {
1205 // Read in the Comparator and any hidden stuff
1206 s.defaultReadObject();
1207
1208 // Same idea as buildFromSorted
1209 @SuppressWarnings("unchecked")
1210 Index<K,V>[] preds = (Index<K,V>[])new Index<?,?>[64];
1211 Node<K,V> bp = new Node<K,V>(null, null, null);
1212 Index<K,V> h = preds[0] = new Index<K,V>(bp, null, null);
1213 Comparator<? super K> cmp = comparator;
1214 K prevKey = null;
1215 long count = 0;
1216
1217 for (;;) {
1218 K k = (K)s.readObject();
1219 if (k == null)
1220 break;
1221 V v = (V)s.readObject();
1222 if (v == null)
1223 throw new NullPointerException();
1224 if (prevKey != null && cpr(cmp, prevKey, k) > 0)
1225 throw new IllegalStateException("out of order");
1226 prevKey = k;
1227 Node<K,V> z = new Node<K,V>(k, v, null);
1228 bp = bp.next = z;
1229 if ((++count & 3L) == 0L) {
1230 long m = count >>> 2;
1231 int i = 0;
1232 Index<K,V> idx = null, q;
1233 do {
1234 idx = new Index<K,V>(z, idx, null);
1235 if ((q = preds[i]) == null)
1236 preds[i] = h = new Index<K,V>(h.node, h, idx);
1237 else
1238 preds[i] = q.right = idx;
1239 } while (++i < preds.length && ((m >>>= 1) & 1L) != 0L);
1240 }
1241 }
1242 if (count != 0L) {
1243 VarHandle.releaseFence();
1244 addCount(count);
1245 head = h;
1246 VarHandle.fullFence();
1247 }
1248 }
1249
1250 /* ------ Map API methods ------ */
1251
1252 /**
1253 * Returns {@code true} if this map contains a mapping for the specified
1254 * key.
1255 *
1256 * @param key key whose presence in this map is to be tested
1257 * @return {@code true} if this map contains a mapping for the specified key
1258 * @throws ClassCastException if the specified key cannot be compared
1259 * with the keys currently in the map
1260 * @throws NullPointerException if the specified key is null
1261 */
1262 public boolean containsKey(Object key) {
1263 return doGet(key) != null;
1264 }
1265
1266 /**
1267 * Returns the value to which the specified key is mapped,
1268 * or {@code null} if this map contains no mapping for the key.
1269 *
1270 * <p>More formally, if this map contains a mapping from a key
1271 * {@code k} to a value {@code v} such that {@code key} compares
1272 * equal to {@code k} according to the map's ordering, then this
1273 * method returns {@code v}; otherwise it returns {@code null}.
1274 * (There can be at most one such mapping.)
1275 *
1276 * @throws ClassCastException if the specified key cannot be compared
1277 * with the keys currently in the map
1278 * @throws NullPointerException if the specified key is null
1279 */
1280 public V get(Object key) {
1281 return doGet(key);
1282 }
1283
1284 /**
1285 * Returns the value to which the specified key is mapped,
1286 * or the given defaultValue if this map contains no mapping for the key.
1287 *
1288 * @param key the key
1289 * @param defaultValue the value to return if this map contains
1290 * no mapping for the given key
1291 * @return the mapping for the key, if present; else the defaultValue
1292 * @throws NullPointerException if the specified key is null
1293 * @since 1.8
1294 */
1295 public V getOrDefault(Object key, V defaultValue) {
1296 V v;
1297 return (v = doGet(key)) == null ? defaultValue : v;
1298 }
1299
1300 /**
1301 * Associates the specified value with the specified key in this map.
1302 * If the map previously contained a mapping for the key, the old
1303 * value is replaced.
1304 *
1305 * @param key key with which the specified value is to be associated
1306 * @param value value to be associated with the specified key
1307 * @return the previous value associated with the specified key, or
1308 * {@code null} if there was no mapping for the key
1309 * @throws ClassCastException if the specified key cannot be compared
1310 * with the keys currently in the map
1311 * @throws NullPointerException if the specified key or value is null
1312 */
1313 public V put(K key, V value) {
1314 if (value == null)
1315 throw new NullPointerException();
1316 return doPut(key, value, false);
1317 }
1318
1319 /**
1320 * Removes the mapping for the specified key from this map if present.
1321 *
1322 * @param key key for which mapping should be removed
1323 * @return the previous value associated with the specified key, or
1324 * {@code null} if there was no mapping for the key
1325 * @throws ClassCastException if the specified key cannot be compared
1326 * with the keys currently in the map
1327 * @throws NullPointerException if the specified key is null
1328 */
1329 public V remove(Object key) {
1330 return doRemove(key, null);
1331 }
1332
1333 /**
1334 * Returns {@code true} if this map maps one or more keys to the
1335 * specified value. This operation requires time linear in the
1336 * map size. Additionally, it is possible for the map to change
1337 * during execution of this method, in which case the returned
1338 * result may be inaccurate.
1339 *
1340 * @param value value whose presence in this map is to be tested
1341 * @return {@code true} if a mapping to {@code value} exists;
1342 * {@code false} otherwise
1343 * @throws NullPointerException if the specified value is null
1344 */
1345 public boolean containsValue(Object value) {
1346 if (value == null)
1347 throw new NullPointerException();
1348 Node<K,V> b, n; V v;
1349 if ((b = baseHead()) != null) {
1350 while ((n = b.next) != null) {
1351 if ((v = n.val) != null && value.equals(v))
1352 return true;
1353 else
1354 b = n;
1355 }
1356 }
1357 return false;
1358 }
1359
1360 /**
1361 * {@inheritDoc}
1362 */
1363 public int size() {
1364 long c;
1365 return ((baseHead() == null) ? 0 :
1366 ((c = getAdderCount()) >= Integer.MAX_VALUE) ?
1367 Integer.MAX_VALUE : (int) c);
1368 }
1369
1370 /**
1371 * {@inheritDoc}
1372 */
1373 public boolean isEmpty() {
1374 return findFirst() == null;
1375 }
1376
1377 /**
1378 * Removes all of the mappings from this map.
1379 */
1380 public void clear() {
1381 Index<K,V> h, r, d; Node<K,V> b;
1382 VarHandle.acquireFence();
1383 while ((h = head) != null) {
1384 if ((r = h.right) != null) // remove indices
1385 RIGHT.compareAndSet(h, r, null);
1386 else if ((d = h.down) != null) // remove levels
1387 HEAD.compareAndSet(this, h, d);
1388 else {
1389 long count = 0L;
1390 if ((b = h.node) != null) { // remove nodes
1391 Node<K,V> n; V v;
1392 while ((n = b.next) != null) {
1393 if ((v = n.val) != null &&
1394 VAL.compareAndSet(n, v, null)) {
1395 --count;
1396 v = null;
1397 }
1398 if (v == null)
1399 unlinkNode(b, n);
1400 }
1401 }
1402 if (count != 0L)
1403 addCount(count);
1404 else
1405 break;
1406 }
1407 }
1408 }
1409
1410 /**
1411 * If the specified key is not already associated with a value,
1412 * attempts to compute its value using the given mapping function
1413 * and enters it into this map unless {@code null}. The function
1414 * is <em>NOT</em> guaranteed to be applied once atomically only
1415 * if the value is not present.
1416 *
1417 * @param key key with which the specified value is to be associated
1418 * @param mappingFunction the function to compute a value
1419 * @return the current (existing or computed) value associated with
1420 * the specified key, or null if the computed value is null
1421 * @throws NullPointerException if the specified key is null
1422 * or the mappingFunction is null
1423 * @since 1.8
1424 */
1425 public V computeIfAbsent(K key,
1426 Function<? super K, ? extends V> mappingFunction) {
1427 if (key == null || mappingFunction == null)
1428 throw new NullPointerException();
1429 V v, p, r;
1430 if ((v = doGet(key)) == null &&
1431 (r = mappingFunction.apply(key)) != null)
1432 v = (p = doPut(key, r, true)) == null ? r : p;
1433 return v;
1434 }
1435
1436 /**
1437 * If the value for the specified key is present, attempts to
1438 * compute a new mapping given the key and its current mapped
1439 * value. The function is <em>NOT</em> guaranteed to be applied
1440 * once atomically.
1441 *
1442 * @param key key with which a value may be associated
1443 * @param remappingFunction the function to compute a value
1444 * @return the new value associated with the specified key, or null if none
1445 * @throws NullPointerException if the specified key is null
1446 * or the remappingFunction is null
1447 * @since 1.8
1448 */
1449 public V computeIfPresent(K key,
1450 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1451 if (key == null || remappingFunction == null)
1452 throw new NullPointerException();
1453 Node<K,V> n; V v;
1454 while ((n = findNode(key)) != null) {
1455 if ((v = n.val) != null) {
1456 V r = remappingFunction.apply(key, v);
1457 if (r != null) {
1458 if (VAL.compareAndSet(n, v, r))
1459 return r;
1460 }
1461 else if (doRemove(key, v) != null)
1462 break;
1463 }
1464 }
1465 return null;
1466 }
1467
1468 /**
1469 * Attempts to compute a mapping for the specified key and its
1470 * current mapped value (or {@code null} if there is no current
1471 * mapping). The function is <em>NOT</em> guaranteed to be applied
1472 * once atomically.
1473 *
1474 * @param key key with which the specified value is to be associated
1475 * @param remappingFunction the function to compute a value
1476 * @return the new value associated with the specified key, or null if none
1477 * @throws NullPointerException if the specified key is null
1478 * or the remappingFunction is null
1479 * @since 1.8
1480 */
1481 public V compute(K key,
1482 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1483 if (key == null || remappingFunction == null)
1484 throw new NullPointerException();
1485 for (;;) {
1486 Node<K,V> n; V v; V r;
1487 if ((n = findNode(key)) == null) {
1488 if ((r = remappingFunction.apply(key, null)) == null)
1489 break;
1490 if (doPut(key, r, true) == null)
1491 return r;
1492 }
1493 else if ((v = n.val) != null) {
1494 if ((r = remappingFunction.apply(key, v)) != null) {
1495 if (VAL.compareAndSet(n, v, r))
1496 return r;
1497 }
1498 else if (doRemove(key, v) != null)
1499 break;
1500 }
1501 }
1502 return null;
1503 }
1504
1505 /**
1506 * If the specified key is not already associated with a value,
1507 * associates it with the given value. Otherwise, replaces the
1508 * value with the results of the given remapping function, or
1509 * removes if {@code null}. The function is <em>NOT</em>
1510 * guaranteed to be applied once atomically.
1511 *
1512 * @param key key with which the specified value is to be associated
1513 * @param value the value to use if absent
1514 * @param remappingFunction the function to recompute a value if present
1515 * @return the new value associated with the specified key, or null if none
1516 * @throws NullPointerException if the specified key or value is null
1517 * or the remappingFunction is null
1518 * @since 1.8
1519 */
1520 public V merge(K key, V value,
1521 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1522 if (key == null || value == null || remappingFunction == null)
1523 throw new NullPointerException();
1524 for (;;) {
1525 Node<K,V> n; V v; V r;
1526 if ((n = findNode(key)) == null) {
1527 if (doPut(key, value, true) == null)
1528 return value;
1529 }
1530 else if ((v = n.val) != null) {
1531 if ((r = remappingFunction.apply(v, value)) != null) {
1532 if (VAL.compareAndSet(n, v, r))
1533 return r;
1534 }
1535 else if (doRemove(key, v) != null)
1536 return null;
1537 }
1538 }
1539 }
1540
1541 /* ---------------- View methods -------------- */
1542
1543 /*
1544 * Note: Lazy initialization works for views because view classes
1545 * are stateless/immutable so it doesn't matter wrt correctness if
1546 * more than one is created (which will only rarely happen). Even
1547 * so, the following idiom conservatively ensures that the method
1548 * returns the one it created if it does so, not one created by
1549 * another racing thread.
1550 */
1551
1552 /**
1553 * Returns a {@link NavigableSet} view of the keys contained in this map.
1554 *
1555 * <p>The set's iterator returns the keys in ascending order.
1556 * The set's spliterator additionally reports {@link Spliterator#CONCURRENT},
1557 * {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
1558 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1559 * key order.
1560 *
1561 * <p>The {@linkplain Spliterator#getComparator() spliterator's comparator}
1562 * is {@code null} if the {@linkplain #comparator() map's comparator}
1563 * is {@code null}.
1564 * Otherwise, the spliterator's comparator is the same as or imposes the
1565 * same total ordering as the map's comparator.
1566 *
1567 * <p>The set is backed by the map, so changes to the map are
1568 * reflected in the set, and vice-versa. The set supports element
1569 * removal, which removes the corresponding mapping from the map,
1570 * via the {@code Iterator.remove}, {@code Set.remove},
1571 * {@code removeAll}, {@code retainAll}, and {@code clear}
1572 * operations. It does not support the {@code add} or {@code addAll}
1573 * operations.
1574 *
1575 * <p>The view's iterators and spliterators are
1576 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1577 *
1578 * <p>This method is equivalent to method {@code navigableKeySet}.
1579 *
1580 * @return a navigable set view of the keys in this map
1581 */
1582 public NavigableSet<K> keySet() {
1583 KeySet<K,V> ks;
1584 if ((ks = keySet) != null) return ks;
1585 return keySet = new KeySet<>(this);
1586 }
1587
1588 public NavigableSet<K> navigableKeySet() {
1589 KeySet<K,V> ks;
1590 if ((ks = keySet) != null) return ks;
1591 return keySet = new KeySet<>(this);
1592 }
1593
1594 /**
1595 * Returns a {@link Collection} view of the values contained in this map.
1596 * <p>The collection's iterator returns the values in ascending order
1597 * of the corresponding keys. The collections's spliterator additionally
1598 * reports {@link Spliterator#CONCURRENT}, {@link Spliterator#NONNULL} and
1599 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1600 * order of the corresponding keys.
1601 *
1602 * <p>The collection is backed by the map, so changes to the map are
1603 * reflected in the collection, and vice-versa. The collection
1604 * supports element removal, which removes the corresponding
1605 * mapping from the map, via the {@code Iterator.remove},
1606 * {@code Collection.remove}, {@code removeAll},
1607 * {@code retainAll} and {@code clear} operations. It does not
1608 * support the {@code add} or {@code addAll} operations.
1609 *
1610 * <p>The view's iterators and spliterators are
1611 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1612 */
1613 public Collection<V> values() {
1614 Values<K,V> vs;
1615 if ((vs = values) != null) return vs;
1616 return values = new Values<>(this);
1617 }
1618
1619 /**
1620 * Returns a {@link Set} view of the mappings contained in this map.
1621 *
1622 * <p>The set's iterator returns the entries in ascending key order. The
1623 * set's spliterator additionally reports {@link Spliterator#CONCURRENT},
1624 * {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
1625 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1626 * key order.
1627 *
1628 * <p>The set is backed by the map, so changes to the map are
1629 * reflected in the set, and vice-versa. The set supports element
1630 * removal, which removes the corresponding mapping from the map,
1631 * via the {@code Iterator.remove}, {@code Set.remove},
1632 * {@code removeAll}, {@code retainAll} and {@code clear}
1633 * operations. It does not support the {@code add} or
1634 * {@code addAll} operations.
1635 *
1636 * <p>The view's iterators and spliterators are
1637 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1638 *
1639 * <p>The {@code Map.Entry} elements traversed by the {@code iterator}
1640 * or {@code spliterator} do <em>not</em> support the {@code setValue}
1641 * operation.
1642 *
1643 * @return a set view of the mappings contained in this map,
1644 * sorted in ascending key order
1645 */
1646 public Set<Map.Entry<K,V>> entrySet() {
1647 EntrySet<K,V> es;
1648 if ((es = entrySet) != null) return es;
1649 return entrySet = new EntrySet<K,V>(this);
1650 }
1651
1652 public ConcurrentNavigableMap<K,V> descendingMap() {
1653 ConcurrentNavigableMap<K,V> dm;
1654 if ((dm = descendingMap) != null) return dm;
1655 return descendingMap =
1656 new SubMap<K,V>(this, null, false, null, false, true);
1657 }
1658
1659 public NavigableSet<K> descendingKeySet() {
1660 return descendingMap().navigableKeySet();
1661 }
1662
1663 /* ---------------- AbstractMap Overrides -------------- */
1664
1665 /**
1666 * Compares the specified object with this map for equality.
1667 * Returns {@code true} if the given object is also a map and the
1668 * two maps represent the same mappings. More formally, two maps
1669 * {@code m1} and {@code m2} represent the same mappings if
1670 * {@code m1.entrySet().equals(m2.entrySet())}. This
1671 * operation may return misleading results if either map is
1672 * concurrently modified during execution of this method.
1673 *
1674 * @param o object to be compared for equality with this map
1675 * @return {@code true} if the specified object is equal to this map
1676 */
1677 public boolean equals(Object o) {
1678 if (o == this)
1679 return true;
1680 if (!(o instanceof Map))
1681 return false;
1682 Map<?,?> m = (Map<?,?>) o;
1683 try {
1684 Comparator<? super K> cmp = comparator;
1685 @SuppressWarnings("unchecked")
1686 Iterator<Map.Entry<?,?>> it =
1687 (Iterator<Map.Entry<?,?>>)m.entrySet().iterator();
1688 if (m instanceof SortedMap &&
1689 ((SortedMap<?,?>)m).comparator() == cmp) {
1690 Node<K,V> b, n;
1691 if ((b = baseHead()) != null) {
1692 while ((n = b.next) != null) {
1693 K k; V v;
1694 if ((v = n.val) != null && (k = n.key) != null) {
1695 if (!it.hasNext())
1696 return false;
1697 Map.Entry<?,?> e = it.next();
1698 Object mk = e.getKey();
1699 Object mv = e.getValue();
1700 if (mk == null || mv == null)
1701 return false;
1702 try {
1703 if (cpr(cmp, k, mk) != 0)
1704 return false;
1705 } catch (ClassCastException cce) {
1706 return false;
1707 }
1708 if (!mv.equals(v))
1709 return false;
1710 }
1711 b = n;
1712 }
1713 }
1714 return !it.hasNext();
1715 }
1716 else {
1717 while (it.hasNext()) {
1718 V v;
1719 Map.Entry<?,?> e = it.next();
1720 Object mk = e.getKey();
1721 Object mv = e.getValue();
1722 if (mk == null || mv == null ||
1723 (v = get(mk)) == null || !v.equals(mv))
1724 return false;
1725 }
1726 Node<K,V> b, n;
1727 if ((b = baseHead()) != null) {
1728 K k; V v; Object mv;
1729 while ((n = b.next) != null) {
1730 if ((v = n.val) != null && (k = n.key) != null &&
1731 ((mv = m.get(k)) == null || !mv.equals(v)))
1732 return false;
1733 b = n;
1734 }
1735 }
1736 return true;
1737 }
1738 } catch (ClassCastException unused) {
1739 return false;
1740 } catch (NullPointerException unused) {
1741 return false;
1742 }
1743 }
1744
1745 /* ------ ConcurrentMap API methods ------ */
1746
1747 /**
1748 * {@inheritDoc}
1749 *
1750 * @return the previous value associated with the specified key,
1751 * or {@code null} if there was no mapping for the key
1752 * @throws ClassCastException if the specified key cannot be compared
1753 * with the keys currently in the map
1754 * @throws NullPointerException if the specified key or value is null
1755 */
1756 public V putIfAbsent(K key, V value) {
1757 if (value == null)
1758 throw new NullPointerException();
1759 return doPut(key, value, true);
1760 }
1761
1762 /**
1763 * {@inheritDoc}
1764 *
1765 * @throws ClassCastException if the specified key cannot be compared
1766 * with the keys currently in the map
1767 * @throws NullPointerException if the specified key is null
1768 */
1769 public boolean remove(Object key, Object value) {
1770 if (key == null)
1771 throw new NullPointerException();
1772 return value != null && doRemove(key, value) != null;
1773 }
1774
1775 /**
1776 * {@inheritDoc}
1777 *
1778 * @throws ClassCastException if the specified key cannot be compared
1779 * with the keys currently in the map
1780 * @throws NullPointerException if any of the arguments are null
1781 */
1782 public boolean replace(K key, V oldValue, V newValue) {
1783 if (key == null || oldValue == null || newValue == null)
1784 throw new NullPointerException();
1785 for (;;) {
1786 Node<K,V> n; V v;
1787 if ((n = findNode(key)) == null)
1788 return false;
1789 if ((v = n.val) != null) {
1790 if (!oldValue.equals(v))
1791 return false;
1792 if (VAL.compareAndSet(n, v, newValue))
1793 return true;
1794 }
1795 }
1796 }
1797
1798 /**
1799 * {@inheritDoc}
1800 *
1801 * @return the previous value associated with the specified key,
1802 * or {@code null} if there was no mapping for the key
1803 * @throws ClassCastException if the specified key cannot be compared
1804 * with the keys currently in the map
1805 * @throws NullPointerException if the specified key or value is null
1806 */
1807 public V replace(K key, V value) {
1808 if (key == null || value == null)
1809 throw new NullPointerException();
1810 for (;;) {
1811 Node<K,V> n; V v;
1812 if ((n = findNode(key)) == null)
1813 return null;
1814 if ((v = n.val) != null && VAL.compareAndSet(n, v, value))
1815 return v;
1816 }
1817 }
1818
1819 /* ------ SortedMap API methods ------ */
1820
1821 public Comparator<? super K> comparator() {
1822 return comparator;
1823 }
1824
1825 /**
1826 * @throws NoSuchElementException {@inheritDoc}
1827 */
1828 public K firstKey() {
1829 Node<K,V> n = findFirst();
1830 if (n == null)
1831 throw new NoSuchElementException();
1832 return n.key;
1833 }
1834
1835 /**
1836 * @throws NoSuchElementException {@inheritDoc}
1837 */
1838 public K lastKey() {
1839 Node<K,V> n = findLast();
1840 if (n == null)
1841 throw new NoSuchElementException();
1842 return n.key;
1843 }
1844
1845 /**
1846 * @throws ClassCastException {@inheritDoc}
1847 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1848 * @throws IllegalArgumentException {@inheritDoc}
1849 */
1850 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
1851 boolean fromInclusive,
1852 K toKey,
1853 boolean toInclusive) {
1854 if (fromKey == null || toKey == null)
1855 throw new NullPointerException();
1856 return new SubMap<K,V>
1857 (this, fromKey, fromInclusive, toKey, toInclusive, false);
1858 }
1859
1860 /**
1861 * @throws ClassCastException {@inheritDoc}
1862 * @throws NullPointerException if {@code toKey} is null
1863 * @throws IllegalArgumentException {@inheritDoc}
1864 */
1865 public ConcurrentNavigableMap<K,V> headMap(K toKey,
1866 boolean inclusive) {
1867 if (toKey == null)
1868 throw new NullPointerException();
1869 return new SubMap<K,V>
1870 (this, null, false, toKey, inclusive, false);
1871 }
1872
1873 /**
1874 * @throws ClassCastException {@inheritDoc}
1875 * @throws NullPointerException if {@code fromKey} is null
1876 * @throws IllegalArgumentException {@inheritDoc}
1877 */
1878 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
1879 boolean inclusive) {
1880 if (fromKey == null)
1881 throw new NullPointerException();
1882 return new SubMap<K,V>
1883 (this, fromKey, inclusive, null, false, false);
1884 }
1885
1886 /**
1887 * @throws ClassCastException {@inheritDoc}
1888 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1889 * @throws IllegalArgumentException {@inheritDoc}
1890 */
1891 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
1892 return subMap(fromKey, true, toKey, false);
1893 }
1894
1895 /**
1896 * @throws ClassCastException {@inheritDoc}
1897 * @throws NullPointerException if {@code toKey} is null
1898 * @throws IllegalArgumentException {@inheritDoc}
1899 */
1900 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
1901 return headMap(toKey, false);
1902 }
1903
1904 /**
1905 * @throws ClassCastException {@inheritDoc}
1906 * @throws NullPointerException if {@code fromKey} is null
1907 * @throws IllegalArgumentException {@inheritDoc}
1908 */
1909 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
1910 return tailMap(fromKey, true);
1911 }
1912
1913 /* ---------------- Relational operations -------------- */
1914
1915 /**
1916 * Returns a key-value mapping associated with the greatest key
1917 * strictly less than the given key, or {@code null} if there is
1918 * no such key. The returned entry does <em>not</em> support the
1919 * {@code Entry.setValue} method.
1920 *
1921 * @throws ClassCastException {@inheritDoc}
1922 * @throws NullPointerException if the specified key is null
1923 */
1924 public Map.Entry<K,V> lowerEntry(K key) {
1925 return findNearEntry(key, LT, comparator);
1926 }
1927
1928 /**
1929 * @throws ClassCastException {@inheritDoc}
1930 * @throws NullPointerException if the specified key is null
1931 */
1932 public K lowerKey(K key) {
1933 Node<K,V> n = findNear(key, LT, comparator);
1934 return (n == null) ? null : n.key;
1935 }
1936
1937 /**
1938 * Returns a key-value mapping associated with the greatest key
1939 * less than or equal to the given key, or {@code null} if there
1940 * is no such key. The returned entry does <em>not</em> support
1941 * the {@code Entry.setValue} method.
1942 *
1943 * @param key the key
1944 * @throws ClassCastException {@inheritDoc}
1945 * @throws NullPointerException if the specified key is null
1946 */
1947 public Map.Entry<K,V> floorEntry(K key) {
1948 return findNearEntry(key, LT|EQ, comparator);
1949 }
1950
1951 /**
1952 * @param key the key
1953 * @throws ClassCastException {@inheritDoc}
1954 * @throws NullPointerException if the specified key is null
1955 */
1956 public K floorKey(K key) {
1957 Node<K,V> n = findNear(key, LT|EQ, comparator);
1958 return (n == null) ? null : n.key;
1959 }
1960
1961 /**
1962 * Returns a key-value mapping associated with the least key
1963 * greater than or equal to the given key, or {@code null} if
1964 * there is no such entry. The returned entry does <em>not</em>
1965 * support the {@code Entry.setValue} method.
1966 *
1967 * @throws ClassCastException {@inheritDoc}
1968 * @throws NullPointerException if the specified key is null
1969 */
1970 public Map.Entry<K,V> ceilingEntry(K key) {
1971 return findNearEntry(key, GT|EQ, comparator);
1972 }
1973
1974 /**
1975 * @throws ClassCastException {@inheritDoc}
1976 * @throws NullPointerException if the specified key is null
1977 */
1978 public K ceilingKey(K key) {
1979 Node<K,V> n = findNear(key, GT|EQ, comparator);
1980 return (n == null) ? null : n.key;
1981 }
1982
1983 /**
1984 * Returns a key-value mapping associated with the least key
1985 * strictly greater than the given key, or {@code null} if there
1986 * is no such key. The returned entry does <em>not</em> support
1987 * the {@code Entry.setValue} method.
1988 *
1989 * @param key the key
1990 * @throws ClassCastException {@inheritDoc}
1991 * @throws NullPointerException if the specified key is null
1992 */
1993 public Map.Entry<K,V> higherEntry(K key) {
1994 return findNearEntry(key, GT, comparator);
1995 }
1996
1997 /**
1998 * @param key the key
1999 * @throws ClassCastException {@inheritDoc}
2000 * @throws NullPointerException if the specified key is null
2001 */
2002 public K higherKey(K key) {
2003 Node<K,V> n = findNear(key, GT, comparator);
2004 return (n == null) ? null : n.key;
2005 }
2006
2007 /**
2008 * Returns a key-value mapping associated with the least
2009 * key in this map, or {@code null} if the map is empty.
2010 * The returned entry does <em>not</em> support
2011 * the {@code Entry.setValue} method.
2012 */
2013 public Map.Entry<K,V> firstEntry() {
2014 return findFirstEntry();
2015 }
2016
2017 /**
2018 * Returns a key-value mapping associated with the greatest
2019 * key in this map, or {@code null} if the map is empty.
2020 * The returned entry does <em>not</em> support
2021 * the {@code Entry.setValue} method.
2022 */
2023 public Map.Entry<K,V> lastEntry() {
2024 return findLastEntry();
2025 }
2026
2027 /**
2028 * Removes and returns a key-value mapping associated with
2029 * the least key in this map, or {@code null} if the map is empty.
2030 * The returned entry does <em>not</em> support
2031 * the {@code Entry.setValue} method.
2032 */
2033 public Map.Entry<K,V> pollFirstEntry() {
2034 return doRemoveFirstEntry();
2035 }
2036
2037 /**
2038 * Removes and returns a key-value mapping associated with
2039 * the greatest key in this map, or {@code null} if the map is empty.
2040 * The returned entry does <em>not</em> support
2041 * the {@code Entry.setValue} method.
2042 */
2043 public Map.Entry<K,V> pollLastEntry() {
2044 return doRemoveLastEntry();
2045 }
2046
2047 /* ---------------- Iterators -------------- */
2048
2049 /**
2050 * Base of iterator classes
2051 */
2052 abstract class Iter<T> implements Iterator<T> {
2053 /** the last node returned by next() */
2054 Node<K,V> lastReturned;
2055 /** the next node to return from next(); */
2056 Node<K,V> next;
2057 /** Cache of next value field to maintain weak consistency */
2058 V nextValue;
2059
2060 /** Initializes ascending iterator for entire range. */
2061 Iter() {
2062 advance(baseHead());
2063 }
2064
2065 public final boolean hasNext() {
2066 return next != null;
2067 }
2068
2069 /** Advances next to higher entry. */
2070 final void advance(Node<K,V> b) {
2071 Node<K,V> n = null;
2072 V v = null;
2073 if ((lastReturned = b) != null) {
2074 while ((n = b.next) != null && (v = n.val) == null)
2075 b = n;
2076 }
2077 nextValue = v;
2078 next = n;
2079 }
2080
2081 public final void remove() {
2082 Node<K,V> n; K k;
2083 if ((n = lastReturned) == null || (k = n.key) == null)
2084 throw new IllegalStateException();
2085 // It would not be worth all of the overhead to directly
2086 // unlink from here. Using remove is fast enough.
2087 ConcurrentSkipListMap.this.remove(k);
2088 lastReturned = null;
2089 }
2090 }
2091
2092 final class ValueIterator extends Iter<V> {
2093 public V next() {
2094 V v;
2095 if ((v = nextValue) == null)
2096 throw new NoSuchElementException();
2097 advance(next);
2098 return v;
2099 }
2100 }
2101
2102 final class KeyIterator extends Iter<K> {
2103 public K next() {
2104 Node<K,V> n;
2105 if ((n = next) == null)
2106 throw new NoSuchElementException();
2107 K k = n.key;
2108 advance(n);
2109 return k;
2110 }
2111 }
2112
2113 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2114 public Map.Entry<K,V> next() {
2115 Node<K,V> n;
2116 if ((n = next) == null)
2117 throw new NoSuchElementException();
2118 K k = n.key;
2119 V v = nextValue;
2120 advance(n);
2121 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2122 }
2123 }
2124
2125 /* ---------------- View Classes -------------- */
2126
2127 /*
2128 * View classes are static, delegating to a ConcurrentNavigableMap
2129 * to allow use by SubMaps, which outweighs the ugliness of
2130 * needing type-tests for Iterator methods.
2131 */
2132
2133 static final <E> List<E> toList(Collection<E> c) {
2134 // Using size() here would be a pessimization.
2135 ArrayList<E> list = new ArrayList<E>();
2136 for (E e : c)
2137 list.add(e);
2138 return list;
2139 }
2140
2141 static final class KeySet<K,V>
2142 extends AbstractSet<K> implements NavigableSet<K> {
2143 final ConcurrentNavigableMap<K,V> m;
2144 KeySet(ConcurrentNavigableMap<K,V> map) { m = map; }
2145 public int size() { return m.size(); }
2146 public boolean isEmpty() { return m.isEmpty(); }
2147 public boolean contains(Object o) { return m.containsKey(o); }
2148 public boolean remove(Object o) { return m.remove(o) != null; }
2149 public void clear() { m.clear(); }
2150 public K lower(K e) { return m.lowerKey(e); }
2151 public K floor(K e) { return m.floorKey(e); }
2152 public K ceiling(K e) { return m.ceilingKey(e); }
2153 public K higher(K e) { return m.higherKey(e); }
2154 public Comparator<? super K> comparator() { return m.comparator(); }
2155 public K first() { return m.firstKey(); }
2156 public K last() { return m.lastKey(); }
2157 public K pollFirst() {
2158 Map.Entry<K,V> e = m.pollFirstEntry();
2159 return (e == null) ? null : e.getKey();
2160 }
2161 public K pollLast() {
2162 Map.Entry<K,V> e = m.pollLastEntry();
2163 return (e == null) ? null : e.getKey();
2164 }
2165 public Iterator<K> iterator() {
2166 return (m instanceof ConcurrentSkipListMap)
2167 ? ((ConcurrentSkipListMap<K,V>)m).new KeyIterator()
2168 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2169 }
2170 public boolean equals(Object o) {
2171 if (o == this)
2172 return true;
2173 if (!(o instanceof Set))
2174 return false;
2175 Collection<?> c = (Collection<?>) o;
2176 try {
2177 return containsAll(c) && c.containsAll(this);
2178 } catch (ClassCastException unused) {
2179 return false;
2180 } catch (NullPointerException unused) {
2181 return false;
2182 }
2183 }
2184 public Object[] toArray() { return toList(this).toArray(); }
2185 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2186 public Iterator<K> descendingIterator() {
2187 return descendingSet().iterator();
2188 }
2189 public NavigableSet<K> subSet(K fromElement,
2190 boolean fromInclusive,
2191 K toElement,
2192 boolean toInclusive) {
2193 return new KeySet<>(m.subMap(fromElement, fromInclusive,
2194 toElement, toInclusive));
2195 }
2196 public NavigableSet<K> headSet(K toElement, boolean inclusive) {
2197 return new KeySet<>(m.headMap(toElement, inclusive));
2198 }
2199 public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
2200 return new KeySet<>(m.tailMap(fromElement, inclusive));
2201 }
2202 public NavigableSet<K> subSet(K fromElement, K toElement) {
2203 return subSet(fromElement, true, toElement, false);
2204 }
2205 public NavigableSet<K> headSet(K toElement) {
2206 return headSet(toElement, false);
2207 }
2208 public NavigableSet<K> tailSet(K fromElement) {
2209 return tailSet(fromElement, true);
2210 }
2211 public NavigableSet<K> descendingSet() {
2212 return new KeySet<>(m.descendingMap());
2213 }
2214
2215 public Spliterator<K> spliterator() {
2216 return (m instanceof ConcurrentSkipListMap)
2217 ? ((ConcurrentSkipListMap<K,V>)m).keySpliterator()
2218 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2219 }
2220 }
2221
2222 static final class Values<K,V> extends AbstractCollection<V> {
2223 final ConcurrentNavigableMap<K,V> m;
2224 Values(ConcurrentNavigableMap<K,V> map) {
2225 m = map;
2226 }
2227 public Iterator<V> iterator() {
2228 return (m instanceof ConcurrentSkipListMap)
2229 ? ((ConcurrentSkipListMap<K,V>)m).new ValueIterator()
2230 : ((SubMap<K,V>)m).new SubMapValueIterator();
2231 }
2232 public int size() { return m.size(); }
2233 public boolean isEmpty() { return m.isEmpty(); }
2234 public boolean contains(Object o) { return m.containsValue(o); }
2235 public void clear() { m.clear(); }
2236 public Object[] toArray() { return toList(this).toArray(); }
2237 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2238
2239 public Spliterator<V> spliterator() {
2240 return (m instanceof ConcurrentSkipListMap)
2241 ? ((ConcurrentSkipListMap<K,V>)m).valueSpliterator()
2242 : ((SubMap<K,V>)m).new SubMapValueIterator();
2243 }
2244
2245 public boolean removeIf(Predicate<? super V> filter) {
2246 if (filter == null) throw new NullPointerException();
2247 if (m instanceof ConcurrentSkipListMap)
2248 return ((ConcurrentSkipListMap<K,V>)m).removeValueIf(filter);
2249 // else use iterator
2250 Iterator<Map.Entry<K,V>> it =
2251 ((SubMap<K,V>)m).new SubMapEntryIterator();
2252 boolean removed = false;
2253 while (it.hasNext()) {
2254 Map.Entry<K,V> e = it.next();
2255 V v = e.getValue();
2256 if (filter.test(v) && m.remove(e.getKey(), v))
2257 removed = true;
2258 }
2259 return removed;
2260 }
2261 }
2262
2263 static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> {
2264 final ConcurrentNavigableMap<K,V> m;
2265 EntrySet(ConcurrentNavigableMap<K,V> map) {
2266 m = map;
2267 }
2268 public Iterator<Map.Entry<K,V>> iterator() {
2269 return (m instanceof ConcurrentSkipListMap)
2270 ? ((ConcurrentSkipListMap<K,V>)m).new EntryIterator()
2271 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2272 }
2273
2274 public boolean contains(Object o) {
2275 if (!(o instanceof Map.Entry))
2276 return false;
2277 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2278 V v = m.get(e.getKey());
2279 return v != null && v.equals(e.getValue());
2280 }
2281 public boolean remove(Object o) {
2282 if (!(o instanceof Map.Entry))
2283 return false;
2284 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2285 return m.remove(e.getKey(),
2286 e.getValue());
2287 }
2288 public boolean isEmpty() {
2289 return m.isEmpty();
2290 }
2291 public int size() {
2292 return m.size();
2293 }
2294 public void clear() {
2295 m.clear();
2296 }
2297 public boolean equals(Object o) {
2298 if (o == this)
2299 return true;
2300 if (!(o instanceof Set))
2301 return false;
2302 Collection<?> c = (Collection<?>) o;
2303 try {
2304 return containsAll(c) && c.containsAll(this);
2305 } catch (ClassCastException unused) {
2306 return false;
2307 } catch (NullPointerException unused) {
2308 return false;
2309 }
2310 }
2311 public Object[] toArray() { return toList(this).toArray(); }
2312 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2313
2314 public Spliterator<Map.Entry<K,V>> spliterator() {
2315 return (m instanceof ConcurrentSkipListMap)
2316 ? ((ConcurrentSkipListMap<K,V>)m).entrySpliterator()
2317 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2318 }
2319 public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
2320 if (filter == null) throw new NullPointerException();
2321 if (m instanceof ConcurrentSkipListMap)
2322 return ((ConcurrentSkipListMap<K,V>)m).removeEntryIf(filter);
2323 // else use iterator
2324 Iterator<Map.Entry<K,V>> it =
2325 ((SubMap<K,V>)m).new SubMapEntryIterator();
2326 boolean removed = false;
2327 while (it.hasNext()) {
2328 Map.Entry<K,V> e = it.next();
2329 if (filter.test(e) && m.remove(e.getKey(), e.getValue()))
2330 removed = true;
2331 }
2332 return removed;
2333 }
2334 }
2335
2336 /**
2337 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2338 * represent a subrange of mappings of their underlying maps.
2339 * Instances of this class support all methods of their underlying
2340 * maps, differing in that mappings outside their range are ignored,
2341 * and attempts to add mappings outside their ranges result in {@link
2342 * IllegalArgumentException}. Instances of this class are constructed
2343 * only using the {@code subMap}, {@code headMap}, and {@code tailMap}
2344 * methods of their underlying maps.
2345 *
2346 * @serial include
2347 */
2348 static final class SubMap<K,V> extends AbstractMap<K,V>
2349 implements ConcurrentNavigableMap<K,V>, Serializable {
2350 private static final long serialVersionUID = -7647078645895051609L;
2351
2352 /** Underlying map */
2353 final ConcurrentSkipListMap<K,V> m;
2354 /** lower bound key, or null if from start */
2355 private final K lo;
2356 /** upper bound key, or null if to end */
2357 private final K hi;
2358 /** inclusion flag for lo */
2359 private final boolean loInclusive;
2360 /** inclusion flag for hi */
2361 private final boolean hiInclusive;
2362 /** direction */
2363 final boolean isDescending;
2364
2365 // Lazily initialized view holders
2366 private transient KeySet<K,V> keySetView;
2367 private transient Values<K,V> valuesView;
2368 private transient EntrySet<K,V> entrySetView;
2369
2370 /**
2371 * Creates a new submap, initializing all fields.
2372 */
2373 SubMap(ConcurrentSkipListMap<K,V> map,
2374 K fromKey, boolean fromInclusive,
2375 K toKey, boolean toInclusive,
2376 boolean isDescending) {
2377 Comparator<? super K> cmp = map.comparator;
2378 if (fromKey != null && toKey != null &&
2379 cpr(cmp, fromKey, toKey) > 0)
2380 throw new IllegalArgumentException("inconsistent range");
2381 this.m = map;
2382 this.lo = fromKey;
2383 this.hi = toKey;
2384 this.loInclusive = fromInclusive;
2385 this.hiInclusive = toInclusive;
2386 this.isDescending = isDescending;
2387 }
2388
2389 /* ---------------- Utilities -------------- */
2390
2391 boolean tooLow(Object key, Comparator<? super K> cmp) {
2392 int c;
2393 return (lo != null && ((c = cpr(cmp, key, lo)) < 0 ||
2394 (c == 0 && !loInclusive)));
2395 }
2396
2397 boolean tooHigh(Object key, Comparator<? super K> cmp) {
2398 int c;
2399 return (hi != null && ((c = cpr(cmp, key, hi)) > 0 ||
2400 (c == 0 && !hiInclusive)));
2401 }
2402
2403 boolean inBounds(Object key, Comparator<? super K> cmp) {
2404 return !tooLow(key, cmp) && !tooHigh(key, cmp);
2405 }
2406
2407 void checkKeyBounds(K key, Comparator<? super K> cmp) {
2408 if (key == null)
2409 throw new NullPointerException();
2410 if (!inBounds(key, cmp))
2411 throw new IllegalArgumentException("key out of range");
2412 }
2413
2414 /**
2415 * Returns true if node key is less than upper bound of range.
2416 */
2417 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n,
2418 Comparator<? super K> cmp) {
2419 if (n == null)
2420 return false;
2421 if (hi == null)
2422 return true;
2423 K k = n.key;
2424 if (k == null) // pass by markers and headers
2425 return true;
2426 int c = cpr(cmp, k, hi);
2427 if (c > 0 || (c == 0 && !hiInclusive))
2428 return false;
2429 return true;
2430 }
2431
2432 /**
2433 * Returns lowest node. This node might not be in range, so
2434 * most usages need to check bounds.
2435 */
2436 ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) {
2437 if (lo == null)
2438 return m.findFirst();
2439 else if (loInclusive)
2440 return m.findNear(lo, GT|EQ, cmp);
2441 else
2442 return m.findNear(lo, GT, cmp);
2443 }
2444
2445 /**
2446 * Returns highest node. This node might not be in range, so
2447 * most usages need to check bounds.
2448 */
2449 ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) {
2450 if (hi == null)
2451 return m.findLast();
2452 else if (hiInclusive)
2453 return m.findNear(hi, LT|EQ, cmp);
2454 else
2455 return m.findNear(hi, LT, cmp);
2456 }
2457
2458 /**
2459 * Returns lowest absolute key (ignoring directionality).
2460 */
2461 K lowestKey() {
2462 Comparator<? super K> cmp = m.comparator;
2463 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2464 if (isBeforeEnd(n, cmp))
2465 return n.key;
2466 else
2467 throw new NoSuchElementException();
2468 }
2469
2470 /**
2471 * Returns highest absolute key (ignoring directionality).
2472 */
2473 K highestKey() {
2474 Comparator<? super K> cmp = m.comparator;
2475 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2476 if (n != null) {
2477 K last = n.key;
2478 if (inBounds(last, cmp))
2479 return last;
2480 }
2481 throw new NoSuchElementException();
2482 }
2483
2484 Map.Entry<K,V> lowestEntry() {
2485 Comparator<? super K> cmp = m.comparator;
2486 for (;;) {
2487 ConcurrentSkipListMap.Node<K,V> n; V v;
2488 if ((n = loNode(cmp)) == null || !isBeforeEnd(n, cmp))
2489 return null;
2490 else if ((v = n.val) != null)
2491 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2492 }
2493 }
2494
2495 Map.Entry<K,V> highestEntry() {
2496 Comparator<? super K> cmp = m.comparator;
2497 for (;;) {
2498 ConcurrentSkipListMap.Node<K,V> n; V v;
2499 if ((n = hiNode(cmp)) == null || !inBounds(n.key, cmp))
2500 return null;
2501 else if ((v = n.val) != null)
2502 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2503 }
2504 }
2505
2506 Map.Entry<K,V> removeLowest() {
2507 Comparator<? super K> cmp = m.comparator;
2508 for (;;) {
2509 ConcurrentSkipListMap.Node<K,V> n; K k; V v;
2510 if ((n = loNode(cmp)) == null)
2511 return null;
2512 else if (!inBounds((k = n.key), cmp))
2513 return null;
2514 else if ((v = m.doRemove(k, null)) != null)
2515 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2516 }
2517 }
2518
2519 Map.Entry<K,V> removeHighest() {
2520 Comparator<? super K> cmp = m.comparator;
2521 for (;;) {
2522 ConcurrentSkipListMap.Node<K,V> n; K k; V v;
2523 if ((n = hiNode(cmp)) == null)
2524 return null;
2525 else if (!inBounds((k = n.key), cmp))
2526 return null;
2527 else if ((v = m.doRemove(k, null)) != null)
2528 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2529 }
2530 }
2531
2532 /**
2533 * Submap version of ConcurrentSkipListMap.findNearEntry.
2534 */
2535 Map.Entry<K,V> getNearEntry(K key, int rel) {
2536 Comparator<? super K> cmp = m.comparator;
2537 if (isDescending) { // adjust relation for direction
2538 if ((rel & LT) == 0)
2539 rel |= LT;
2540 else
2541 rel &= ~LT;
2542 }
2543 if (tooLow(key, cmp))
2544 return ((rel & LT) != 0) ? null : lowestEntry();
2545 if (tooHigh(key, cmp))
2546 return ((rel & LT) != 0) ? highestEntry() : null;
2547 AbstractMap.SimpleImmutableEntry<K,V> e =
2548 m.findNearEntry(key, rel, cmp);
2549 if (e == null || !inBounds(e.getKey(), cmp))
2550 return null;
2551 else
2552 return e;
2553 }
2554
2555 // Almost the same as getNearEntry, except for keys
2556 K getNearKey(K key, int rel) {
2557 Comparator<? super K> cmp = m.comparator;
2558 if (isDescending) { // adjust relation for direction
2559 if ((rel & LT) == 0)
2560 rel |= LT;
2561 else
2562 rel &= ~LT;
2563 }
2564 if (tooLow(key, cmp)) {
2565 if ((rel & LT) == 0) {
2566 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2567 if (isBeforeEnd(n, cmp))
2568 return n.key;
2569 }
2570 return null;
2571 }
2572 if (tooHigh(key, cmp)) {
2573 if ((rel & LT) != 0) {
2574 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2575 if (n != null) {
2576 K last = n.key;
2577 if (inBounds(last, cmp))
2578 return last;
2579 }
2580 }
2581 return null;
2582 }
2583 for (;;) {
2584 Node<K,V> n = m.findNear(key, rel, cmp);
2585 if (n == null || !inBounds(n.key, cmp))
2586 return null;
2587 if (n.val != null)
2588 return n.key;
2589 }
2590 }
2591
2592 /* ---------------- Map API methods -------------- */
2593
2594 public boolean containsKey(Object key) {
2595 if (key == null) throw new NullPointerException();
2596 return inBounds(key, m.comparator) && m.containsKey(key);
2597 }
2598
2599 public V get(Object key) {
2600 if (key == null) throw new NullPointerException();
2601 return (!inBounds(key, m.comparator)) ? null : m.get(key);
2602 }
2603
2604 public V put(K key, V value) {
2605 checkKeyBounds(key, m.comparator);
2606 return m.put(key, value);
2607 }
2608
2609 public V remove(Object key) {
2610 return (!inBounds(key, m.comparator)) ? null : m.remove(key);
2611 }
2612
2613 public int size() {
2614 Comparator<? super K> cmp = m.comparator;
2615 long count = 0;
2616 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2617 isBeforeEnd(n, cmp);
2618 n = n.next) {
2619 if (n.val != null)
2620 ++count;
2621 }
2622 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2623 }
2624
2625 public boolean isEmpty() {
2626 Comparator<? super K> cmp = m.comparator;
2627 return !isBeforeEnd(loNode(cmp), cmp);
2628 }
2629
2630 public boolean containsValue(Object value) {
2631 if (value == null)
2632 throw new NullPointerException();
2633 Comparator<? super K> cmp = m.comparator;
2634 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2635 isBeforeEnd(n, cmp);
2636 n = n.next) {
2637 V v = n.val;
2638 if (v != null && value.equals(v))
2639 return true;
2640 }
2641 return false;
2642 }
2643
2644 public void clear() {
2645 Comparator<? super K> cmp = m.comparator;
2646 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2647 isBeforeEnd(n, cmp);
2648 n = n.next) {
2649 if (n.val != null)
2650 m.remove(n.key);
2651 }
2652 }
2653
2654 /* ---------------- ConcurrentMap API methods -------------- */
2655
2656 public V putIfAbsent(K key, V value) {
2657 checkKeyBounds(key, m.comparator);
2658 return m.putIfAbsent(key, value);
2659 }
2660
2661 public boolean remove(Object key, Object value) {
2662 return inBounds(key, m.comparator) && m.remove(key, value);
2663 }
2664
2665 public boolean replace(K key, V oldValue, V newValue) {
2666 checkKeyBounds(key, m.comparator);
2667 return m.replace(key, oldValue, newValue);
2668 }
2669
2670 public V replace(K key, V value) {
2671 checkKeyBounds(key, m.comparator);
2672 return m.replace(key, value);
2673 }
2674
2675 /* ---------------- SortedMap API methods -------------- */
2676
2677 public Comparator<? super K> comparator() {
2678 Comparator<? super K> cmp = m.comparator();
2679 if (isDescending)
2680 return Collections.reverseOrder(cmp);
2681 else
2682 return cmp;
2683 }
2684
2685 /**
2686 * Utility to create submaps, where given bounds override
2687 * unbounded(null) ones and/or are checked against bounded ones.
2688 */
2689 SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive,
2690 K toKey, boolean toInclusive) {
2691 Comparator<? super K> cmp = m.comparator;
2692 if (isDescending) { // flip senses
2693 K tk = fromKey;
2694 fromKey = toKey;
2695 toKey = tk;
2696 boolean ti = fromInclusive;
2697 fromInclusive = toInclusive;
2698 toInclusive = ti;
2699 }
2700 if (lo != null) {
2701 if (fromKey == null) {
2702 fromKey = lo;
2703 fromInclusive = loInclusive;
2704 }
2705 else {
2706 int c = cpr(cmp, fromKey, lo);
2707 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2708 throw new IllegalArgumentException("key out of range");
2709 }
2710 }
2711 if (hi != null) {
2712 if (toKey == null) {
2713 toKey = hi;
2714 toInclusive = hiInclusive;
2715 }
2716 else {
2717 int c = cpr(cmp, toKey, hi);
2718 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2719 throw new IllegalArgumentException("key out of range");
2720 }
2721 }
2722 return new SubMap<K,V>(m, fromKey, fromInclusive,
2723 toKey, toInclusive, isDescending);
2724 }
2725
2726 public SubMap<K,V> subMap(K fromKey, boolean fromInclusive,
2727 K toKey, boolean toInclusive) {
2728 if (fromKey == null || toKey == null)
2729 throw new NullPointerException();
2730 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2731 }
2732
2733 public SubMap<K,V> headMap(K toKey, boolean inclusive) {
2734 if (toKey == null)
2735 throw new NullPointerException();
2736 return newSubMap(null, false, toKey, inclusive);
2737 }
2738
2739 public SubMap<K,V> tailMap(K fromKey, boolean inclusive) {
2740 if (fromKey == null)
2741 throw new NullPointerException();
2742 return newSubMap(fromKey, inclusive, null, false);
2743 }
2744
2745 public SubMap<K,V> subMap(K fromKey, K toKey) {
2746 return subMap(fromKey, true, toKey, false);
2747 }
2748
2749 public SubMap<K,V> headMap(K toKey) {
2750 return headMap(toKey, false);
2751 }
2752
2753 public SubMap<K,V> tailMap(K fromKey) {
2754 return tailMap(fromKey, true);
2755 }
2756
2757 public SubMap<K,V> descendingMap() {
2758 return new SubMap<K,V>(m, lo, loInclusive,
2759 hi, hiInclusive, !isDescending);
2760 }
2761
2762 /* ---------------- Relational methods -------------- */
2763
2764 public Map.Entry<K,V> ceilingEntry(K key) {
2765 return getNearEntry(key, GT|EQ);
2766 }
2767
2768 public K ceilingKey(K key) {
2769 return getNearKey(key, GT|EQ);
2770 }
2771
2772 public Map.Entry<K,V> lowerEntry(K key) {
2773 return getNearEntry(key, LT);
2774 }
2775
2776 public K lowerKey(K key) {
2777 return getNearKey(key, LT);
2778 }
2779
2780 public Map.Entry<K,V> floorEntry(K key) {
2781 return getNearEntry(key, LT|EQ);
2782 }
2783
2784 public K floorKey(K key) {
2785 return getNearKey(key, LT|EQ);
2786 }
2787
2788 public Map.Entry<K,V> higherEntry(K key) {
2789 return getNearEntry(key, GT);
2790 }
2791
2792 public K higherKey(K key) {
2793 return getNearKey(key, GT);
2794 }
2795
2796 public K firstKey() {
2797 return isDescending ? highestKey() : lowestKey();
2798 }
2799
2800 public K lastKey() {
2801 return isDescending ? lowestKey() : highestKey();
2802 }
2803
2804 public Map.Entry<K,V> firstEntry() {
2805 return isDescending ? highestEntry() : lowestEntry();
2806 }
2807
2808 public Map.Entry<K,V> lastEntry() {
2809 return isDescending ? lowestEntry() : highestEntry();
2810 }
2811
2812 public Map.Entry<K,V> pollFirstEntry() {
2813 return isDescending ? removeHighest() : removeLowest();
2814 }
2815
2816 public Map.Entry<K,V> pollLastEntry() {
2817 return isDescending ? removeLowest() : removeHighest();
2818 }
2819
2820 /* ---------------- Submap Views -------------- */
2821
2822 public NavigableSet<K> keySet() {
2823 KeySet<K,V> ks;
2824 if ((ks = keySetView) != null) return ks;
2825 return keySetView = new KeySet<>(this);
2826 }
2827
2828 public NavigableSet<K> navigableKeySet() {
2829 KeySet<K,V> ks;
2830 if ((ks = keySetView) != null) return ks;
2831 return keySetView = new KeySet<>(this);
2832 }
2833
2834 public Collection<V> values() {
2835 Values<K,V> vs;
2836 if ((vs = valuesView) != null) return vs;
2837 return valuesView = new Values<>(this);
2838 }
2839
2840 public Set<Map.Entry<K,V>> entrySet() {
2841 EntrySet<K,V> es;
2842 if ((es = entrySetView) != null) return es;
2843 return entrySetView = new EntrySet<K,V>(this);
2844 }
2845
2846 public NavigableSet<K> descendingKeySet() {
2847 return descendingMap().navigableKeySet();
2848 }
2849
2850 /**
2851 * Variant of main Iter class to traverse through submaps.
2852 * Also serves as back-up Spliterator for views.
2853 */
2854 abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> {
2855 /** the last node returned by next() */
2856 Node<K,V> lastReturned;
2857 /** the next node to return from next(); */
2858 Node<K,V> next;
2859 /** Cache of next value field to maintain weak consistency */
2860 V nextValue;
2861
2862 SubMapIter() {
2863 VarHandle.acquireFence();
2864 Comparator<? super K> cmp = m.comparator;
2865 for (;;) {
2866 next = isDescending ? hiNode(cmp) : loNode(cmp);
2867 if (next == null)
2868 break;
2869 V x = next.val;
2870 if (x != null) {
2871 if (! inBounds(next.key, cmp))
2872 next = null;
2873 else
2874 nextValue = x;
2875 break;
2876 }
2877 }
2878 }
2879
2880 public final boolean hasNext() {
2881 return next != null;
2882 }
2883
2884 final void advance() {
2885 if (next == null)
2886 throw new NoSuchElementException();
2887 lastReturned = next;
2888 if (isDescending)
2889 descend();
2890 else
2891 ascend();
2892 }
2893
2894 private void ascend() {
2895 Comparator<? super K> cmp = m.comparator;
2896 for (;;) {
2897 next = next.next;
2898 if (next == null)
2899 break;
2900 V x = next.val;
2901 if (x != null) {
2902 if (tooHigh(next.key, cmp))
2903 next = null;
2904 else
2905 nextValue = x;
2906 break;
2907 }
2908 }
2909 }
2910
2911 private void descend() {
2912 Comparator<? super K> cmp = m.comparator;
2913 for (;;) {
2914 next = m.findNear(lastReturned.key, LT, cmp);
2915 if (next == null)
2916 break;
2917 V x = next.val;
2918 if (x != null) {
2919 if (tooLow(next.key, cmp))
2920 next = null;
2921 else
2922 nextValue = x;
2923 break;
2924 }
2925 }
2926 }
2927
2928 public void remove() {
2929 Node<K,V> l = lastReturned;
2930 if (l == null)
2931 throw new IllegalStateException();
2932 m.remove(l.key);
2933 lastReturned = null;
2934 }
2935
2936 public Spliterator<T> trySplit() {
2937 return null;
2938 }
2939
2940 public boolean tryAdvance(Consumer<? super T> action) {
2941 if (hasNext()) {
2942 action.accept(next());
2943 return true;
2944 }
2945 return false;
2946 }
2947
2948 public void forEachRemaining(Consumer<? super T> action) {
2949 while (hasNext())
2950 action.accept(next());
2951 }
2952
2953 public long estimateSize() {
2954 return Long.MAX_VALUE;
2955 }
2956
2957 }
2958
2959 final class SubMapValueIterator extends SubMapIter<V> {
2960 public V next() {
2961 V v = nextValue;
2962 advance();
2963 return v;
2964 }
2965 public int characteristics() {
2966 return 0;
2967 }
2968 }
2969
2970 final class SubMapKeyIterator extends SubMapIter<K> {
2971 public K next() {
2972 Node<K,V> n = next;
2973 advance();
2974 return n.key;
2975 }
2976 public int characteristics() {
2977 return Spliterator.DISTINCT | Spliterator.ORDERED |
2978 Spliterator.SORTED;
2979 }
2980 public final Comparator<? super K> getComparator() {
2981 return SubMap.this.comparator();
2982 }
2983 }
2984
2985 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
2986 public Map.Entry<K,V> next() {
2987 Node<K,V> n = next;
2988 V v = nextValue;
2989 advance();
2990 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2991 }
2992 public int characteristics() {
2993 return Spliterator.DISTINCT;
2994 }
2995 }
2996 }
2997
2998 // default Map method overrides
2999
3000 public void forEach(BiConsumer<? super K, ? super V> action) {
3001 if (action == null) throw new NullPointerException();
3002 Node<K,V> b, n; V v;
3003 if ((b = baseHead()) != null) {
3004 while ((n = b.next) != null) {
3005 if ((v = n.val) != null)
3006 action.accept(n.key, v);
3007 b = n;
3008 }
3009 }
3010 }
3011
3012 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3013 if (function == null) throw new NullPointerException();
3014 Node<K,V> b, n; V v;
3015 if ((b = baseHead()) != null) {
3016 while ((n = b.next) != null) {
3017 while ((v = n.val) != null) {
3018 V r = function.apply(n.key, v);
3019 if (r == null) throw new NullPointerException();
3020 if (VAL.compareAndSet(n, v, r))
3021 break;
3022 }
3023 b = n;
3024 }
3025 }
3026 }
3027
3028 /**
3029 * Helper method for EntrySet.removeIf.
3030 */
3031 boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
3032 if (function == null) throw new NullPointerException();
3033 boolean removed = false;
3034 Node<K,V> b, n; V v;
3035 if ((b = baseHead()) != null) {
3036 while ((n = b.next) != null) {
3037 if ((v = n.val) != null) {
3038 K k = n.key;
3039 Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
3040 if (function.test(e) && remove(k, v))
3041 removed = true;
3042 }
3043 b = n;
3044 }
3045 }
3046 return removed;
3047 }
3048
3049 /**
3050 * Helper method for Values.removeIf.
3051 */
3052 boolean removeValueIf(Predicate<? super V> function) {
3053 if (function == null) throw new NullPointerException();
3054 boolean removed = false;
3055 Node<K,V> b, n; V v;
3056 if ((b = baseHead()) != null) {
3057 while ((n = b.next) != null) {
3058 if ((v = n.val) != null && function.test(v) && remove(n.key, v))
3059 removed = true;
3060 b = n;
3061 }
3062 }
3063 return removed;
3064 }
3065
3066 /**
3067 * Base class providing common structure for Spliterators.
3068 * (Although not all that much common functionality; as usual for
3069 * view classes, details annoyingly vary in key, value, and entry
3070 * subclasses in ways that are not worth abstracting out for
3071 * internal classes.)
3072 *
3073 * The basic split strategy is to recursively descend from top
3074 * level, row by row, descending to next row when either split
3075 * off, or the end of row is encountered. Control of the number of
3076 * splits relies on some statistical estimation: The expected
3077 * remaining number of elements of a skip list when advancing
3078 * either across or down decreases by about 25%.
3079 */
3080 abstract static class CSLMSpliterator<K,V> {
3081 final Comparator<? super K> comparator;
3082 final K fence; // exclusive upper bound for keys, or null if to end
3083 Index<K,V> row; // the level to split out
3084 Node<K,V> current; // current traversal node; initialize at origin
3085 long est; // size estimate
3086 CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3087 Node<K,V> origin, K fence, long est) {
3088 this.comparator = comparator; this.row = row;
3089 this.current = origin; this.fence = fence; this.est = est;
3090 }
3091
3092 public final long estimateSize() { return est; }
3093 }
3094
3095 static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
3096 implements Spliterator<K> {
3097 KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3098 Node<K,V> origin, K fence, long est) {
3099 super(comparator, row, origin, fence, est);
3100 }
3101
3102 public KeySpliterator<K,V> trySplit() {
3103 Node<K,V> e; K ek;
3104 Comparator<? super K> cmp = comparator;
3105 K f = fence;
3106 if ((e = current) != null && (ek = e.key) != null) {
3107 for (Index<K,V> q = row; q != null; q = row = q.down) {
3108 Index<K,V> s; Node<K,V> b, n; K sk;
3109 if ((s = q.right) != null && (b = s.node) != null &&
3110 (n = b.next) != null && n.val != null &&
3111 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3112 (f == null || cpr(cmp, sk, f) < 0)) {
3113 current = n;
3114 Index<K,V> r = q.down;
3115 row = (s.right != null) ? s : s.down;
3116 est -= est >>> 2;
3117 return new KeySpliterator<K,V>(cmp, r, e, sk, est);
3118 }
3119 }
3120 }
3121 return null;
3122 }
3123
3124 public void forEachRemaining(Consumer<? super K> action) {
3125 if (action == null) throw new NullPointerException();
3126 Comparator<? super K> cmp = comparator;
3127 K f = fence;
3128 Node<K,V> e = current;
3129 current = null;
3130 for (; e != null; e = e.next) {
3131 K k;
3132 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3133 break;
3134 if (e.val != null)
3135 action.accept(k);
3136 }
3137 }
3138
3139 public boolean tryAdvance(Consumer<? super K> action) {
3140 if (action == null) throw new NullPointerException();
3141 Comparator<? super K> cmp = comparator;
3142 K f = fence;
3143 Node<K,V> e = current;
3144 for (; e != null; e = e.next) {
3145 K k;
3146 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3147 e = null;
3148 break;
3149 }
3150 if (e.val != null) {
3151 current = e.next;
3152 action.accept(k);
3153 return true;
3154 }
3155 }
3156 current = e;
3157 return false;
3158 }
3159
3160 public int characteristics() {
3161 return Spliterator.DISTINCT | Spliterator.SORTED |
3162 Spliterator.ORDERED | Spliterator.CONCURRENT |
3163 Spliterator.NONNULL;
3164 }
3165
3166 public final Comparator<? super K> getComparator() {
3167 return comparator;
3168 }
3169 }
3170 // factory method for KeySpliterator
3171 final KeySpliterator<K,V> keySpliterator() {
3172 Index<K,V> h; Node<K,V> n; long est;
3173 VarHandle.acquireFence();
3174 if ((h = head) == null) {
3175 n = null;
3176 est = 0L;
3177 }
3178 else {
3179 n = h.node;
3180 est = getAdderCount();
3181 }
3182 return new KeySpliterator<K,V>(comparator, h, n, null, est);
3183 }
3184
3185 static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
3186 implements Spliterator<V> {
3187 ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3188 Node<K,V> origin, K fence, long est) {
3189 super(comparator, row, origin, fence, est);
3190 }
3191
3192 public ValueSpliterator<K,V> trySplit() {
3193 Node<K,V> e; K ek;
3194 Comparator<? super K> cmp = comparator;
3195 K f = fence;
3196 if ((e = current) != null && (ek = e.key) != null) {
3197 for (Index<K,V> q = row; q != null; q = row = q.down) {
3198 Index<K,V> s; Node<K,V> b, n; K sk;
3199 if ((s = q.right) != null && (b = s.node) != null &&
3200 (n = b.next) != null && n.val != null &&
3201 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3202 (f == null || cpr(cmp, sk, f) < 0)) {
3203 current = n;
3204 Index<K,V> r = q.down;
3205 row = (s.right != null) ? s : s.down;
3206 est -= est >>> 2;
3207 return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
3208 }
3209 }
3210 }
3211 return null;
3212 }
3213
3214 public void forEachRemaining(Consumer<? super V> action) {
3215 if (action == null) throw new NullPointerException();
3216 Comparator<? super K> cmp = comparator;
3217 K f = fence;
3218 Node<K,V> e = current;
3219 current = null;
3220 for (; e != null; e = e.next) {
3221 K k; V v;
3222 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3223 break;
3224 if ((v = e.val) != null)
3225 action.accept(v);
3226 }
3227 }
3228
3229 public boolean tryAdvance(Consumer<? super V> action) {
3230 if (action == null) throw new NullPointerException();
3231 Comparator<? super K> cmp = comparator;
3232 K f = fence;
3233 Node<K,V> e = current;
3234 for (; e != null; e = e.next) {
3235 K k; V v;
3236 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3237 e = null;
3238 break;
3239 }
3240 if ((v = e.val) != null) {
3241 current = e.next;
3242 action.accept(v);
3243 return true;
3244 }
3245 }
3246 current = e;
3247 return false;
3248 }
3249
3250 public int characteristics() {
3251 return Spliterator.CONCURRENT | Spliterator.ORDERED |
3252 Spliterator.NONNULL;
3253 }
3254 }
3255
3256 // Almost the same as keySpliterator()
3257 final ValueSpliterator<K,V> valueSpliterator() {
3258 Index<K,V> h; Node<K,V> n; long est;
3259 VarHandle.acquireFence();
3260 if ((h = head) == null) {
3261 n = null;
3262 est = 0L;
3263 }
3264 else {
3265 n = h.node;
3266 est = getAdderCount();
3267 }
3268 return new ValueSpliterator<K,V>(comparator, h, n, null, est);
3269 }
3270
3271 static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
3272 implements Spliterator<Map.Entry<K,V>> {
3273 EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3274 Node<K,V> origin, K fence, long est) {
3275 super(comparator, row, origin, fence, est);
3276 }
3277
3278 public EntrySpliterator<K,V> trySplit() {
3279 Node<K,V> e; K ek;
3280 Comparator<? super K> cmp = comparator;
3281 K f = fence;
3282 if ((e = current) != null && (ek = e.key) != null) {
3283 for (Index<K,V> q = row; q != null; q = row = q.down) {
3284 Index<K,V> s; Node<K,V> b, n; K sk;
3285 if ((s = q.right) != null && (b = s.node) != null &&
3286 (n = b.next) != null && n.val != null &&
3287 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3288 (f == null || cpr(cmp, sk, f) < 0)) {
3289 current = n;
3290 Index<K,V> r = q.down;
3291 row = (s.right != null) ? s : s.down;
3292 est -= est >>> 2;
3293 return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
3294 }
3295 }
3296 }
3297 return null;
3298 }
3299
3300 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3301 if (action == null) throw new NullPointerException();
3302 Comparator<? super K> cmp = comparator;
3303 K f = fence;
3304 Node<K,V> e = current;
3305 current = null;
3306 for (; e != null; e = e.next) {
3307 K k; V v;
3308 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3309 break;
3310 if ((v = e.val) != null) {
3311 action.accept
3312 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
3313 }
3314 }
3315 }
3316
3317 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3318 if (action == null) throw new NullPointerException();
3319 Comparator<? super K> cmp = comparator;
3320 K f = fence;
3321 Node<K,V> e = current;
3322 for (; e != null; e = e.next) {
3323 K k; V v;
3324 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3325 e = null;
3326 break;
3327 }
3328 if ((v = e.val) != null) {
3329 current = e.next;
3330 action.accept
3331 (new AbstractMap.SimpleImmutableEntry<K,V>(k, v));
3332 return true;
3333 }
3334 }
3335 current = e;
3336 return false;
3337 }
3338
3339 public int characteristics() {
3340 return Spliterator.DISTINCT | Spliterator.SORTED |
3341 Spliterator.ORDERED | Spliterator.CONCURRENT |
3342 Spliterator.NONNULL;
3343 }
3344
3345 public final Comparator<Map.Entry<K,V>> getComparator() {
3346 // Adapt or create a key-based comparator
3347 if (comparator != null) {
3348 return Map.Entry.comparingByKey(comparator);
3349 }
3350 else {
3351 return (Comparator<Map.Entry<K,V>> & Serializable) (e1, e2) -> {
3352 @SuppressWarnings("unchecked")
3353 Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3354 return k1.compareTo(e2.getKey());
3355 };
3356 }
3357 }
3358 }
3359
3360 // Almost the same as keySpliterator()
3361 final EntrySpliterator<K,V> entrySpliterator() {
3362 Index<K,V> h; Node<K,V> n; long est;
3363 VarHandle.acquireFence();
3364 if ((h = head) == null) {
3365 n = null;
3366 est = 0L;
3367 }
3368 else {
3369 n = h.node;
3370 est = getAdderCount();
3371 }
3372 return new EntrySpliterator<K,V>(comparator, h, n, null, est);
3373 }
3374
3375 // VarHandle mechanics
3376 private static final VarHandle HEAD;
3377 private static final VarHandle ADDER;
3378 private static final VarHandle NEXT;
3379 private static final VarHandle VAL;
3380 private static final VarHandle RIGHT;
3381 static {
3382 try {
3383 MethodHandles.Lookup l = MethodHandles.lookup();
3384 HEAD = l.findVarHandle(ConcurrentSkipListMap.class, "head",
3385 Index.class);
3386 ADDER = l.findVarHandle(ConcurrentSkipListMap.class, "adder",
3387 LongAdder.class);
3388 NEXT = l.findVarHandle(Node.class, "next", Node.class);
3389 VAL = l.findVarHandle(Node.class, "val", Object.class);
3390 RIGHT = l.findVarHandle(Index.class, "right", Index.class);
3391 } catch (ReflectiveOperationException e) {
3392 throw new Error(e);
3393 }
3394 }
3395 }