ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.166
Committed: Sat Mar 11 17:36:10 2017 UTC (7 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.165: +0 -1 lines
Log Message:
fix unused imports reported by errorprone [RemoveUnusedImports]

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