ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.167
Committed: Wed Apr 19 23:45:51 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.166: +5 -3 lines
Log Message:
Redo @link and @linkplain; one @link was pointing to the wrong poll method

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.
1796 *
1797 * <p>The {@linkplain Spliterator#getComparator() spliterator's comparator}
1798 * is {@code null} if the {@linkplain #comparator() map's comparator}
1799 * is {@code null}.
1800 * Otherwise, the spliterator's comparator is the same as or imposes the
1801 * same total ordering as the map's comparator.
1802 *
1803 * <p>The set is backed by the map, so changes to the map are
1804 * reflected in the set, and vice-versa. The set supports element
1805 * removal, which removes the corresponding mapping from the map,
1806 * via the {@code Iterator.remove}, {@code Set.remove},
1807 * {@code removeAll}, {@code retainAll}, and {@code clear}
1808 * operations. It does not support the {@code add} or {@code addAll}
1809 * operations.
1810 *
1811 * <p>The view's iterators and spliterators are
1812 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1813 *
1814 * <p>This method is equivalent to method {@code navigableKeySet}.
1815 *
1816 * @return a navigable set view of the keys in this map
1817 */
1818 public NavigableSet<K> keySet() {
1819 KeySet<K,V> ks;
1820 if ((ks = keySet) != null) return ks;
1821 return keySet = new KeySet<>(this);
1822 }
1823
1824 public NavigableSet<K> navigableKeySet() {
1825 KeySet<K,V> ks;
1826 if ((ks = keySet) != null) return ks;
1827 return keySet = new KeySet<>(this);
1828 }
1829
1830 /**
1831 * Returns a {@link Collection} view of the values contained in this map.
1832 * <p>The collection's iterator returns the values in ascending order
1833 * of the corresponding keys. The collections's spliterator additionally
1834 * reports {@link Spliterator#CONCURRENT}, {@link Spliterator#NONNULL} and
1835 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1836 * order of the corresponding keys.
1837 *
1838 * <p>The collection is backed by the map, so changes to the map are
1839 * reflected in the collection, and vice-versa. The collection
1840 * supports element removal, which removes the corresponding
1841 * mapping from the map, via the {@code Iterator.remove},
1842 * {@code Collection.remove}, {@code removeAll},
1843 * {@code retainAll} and {@code clear} operations. It does not
1844 * support the {@code add} or {@code addAll} operations.
1845 *
1846 * <p>The view's iterators and spliterators are
1847 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1848 */
1849 public Collection<V> values() {
1850 Values<K,V> vs;
1851 if ((vs = values) != null) return vs;
1852 return values = new Values<>(this);
1853 }
1854
1855 /**
1856 * Returns a {@link Set} view of the mappings contained in this map.
1857 *
1858 * <p>The set's iterator returns the entries in ascending key order. The
1859 * set's spliterator additionally reports {@link Spliterator#CONCURRENT},
1860 * {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
1861 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1862 * key order.
1863 *
1864 * <p>The set is backed by the map, so changes to the map are
1865 * reflected in the set, and vice-versa. The set supports element
1866 * removal, which removes the corresponding mapping from the map,
1867 * via the {@code Iterator.remove}, {@code Set.remove},
1868 * {@code removeAll}, {@code retainAll} and {@code clear}
1869 * operations. It does not support the {@code add} or
1870 * {@code addAll} operations.
1871 *
1872 * <p>The view's iterators and spliterators are
1873 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1874 *
1875 * <p>The {@code Map.Entry} elements traversed by the {@code iterator}
1876 * or {@code spliterator} do <em>not</em> support the {@code setValue}
1877 * operation.
1878 *
1879 * @return a set view of the mappings contained in this map,
1880 * sorted in ascending key order
1881 */
1882 public Set<Map.Entry<K,V>> entrySet() {
1883 EntrySet<K,V> es;
1884 if ((es = entrySet) != null) return es;
1885 return entrySet = new EntrySet<K,V>(this);
1886 }
1887
1888 public ConcurrentNavigableMap<K,V> descendingMap() {
1889 ConcurrentNavigableMap<K,V> dm;
1890 if ((dm = descendingMap) != null) return dm;
1891 return descendingMap =
1892 new SubMap<K,V>(this, null, false, null, false, true);
1893 }
1894
1895 public NavigableSet<K> descendingKeySet() {
1896 return descendingMap().navigableKeySet();
1897 }
1898
1899 /* ---------------- AbstractMap Overrides -------------- */
1900
1901 /**
1902 * Compares the specified object with this map for equality.
1903 * Returns {@code true} if the given object is also a map and the
1904 * two maps represent the same mappings. More formally, two maps
1905 * {@code m1} and {@code m2} represent the same mappings if
1906 * {@code m1.entrySet().equals(m2.entrySet())}. This
1907 * operation may return misleading results if either map is
1908 * concurrently modified during execution of this method.
1909 *
1910 * @param o object to be compared for equality with this map
1911 * @return {@code true} if the specified object is equal to this map
1912 */
1913 public boolean equals(Object o) {
1914 if (o == this)
1915 return true;
1916 if (!(o instanceof Map))
1917 return false;
1918 Map<?,?> m = (Map<?,?>) o;
1919 try {
1920 for (Map.Entry<K,V> e : this.entrySet())
1921 if (! e.getValue().equals(m.get(e.getKey())))
1922 return false;
1923 for (Map.Entry<?,?> e : m.entrySet()) {
1924 Object k = e.getKey();
1925 Object v = e.getValue();
1926 if (k == null || v == null || !v.equals(get(k)))
1927 return false;
1928 }
1929 return true;
1930 } catch (ClassCastException unused) {
1931 return false;
1932 } catch (NullPointerException unused) {
1933 return false;
1934 }
1935 }
1936
1937 /* ------ ConcurrentMap API methods ------ */
1938
1939 /**
1940 * {@inheritDoc}
1941 *
1942 * @return the previous value associated with the specified key,
1943 * or {@code null} if there was no mapping for the key
1944 * @throws ClassCastException if the specified key cannot be compared
1945 * with the keys currently in the map
1946 * @throws NullPointerException if the specified key or value is null
1947 */
1948 public V putIfAbsent(K key, V value) {
1949 if (value == null)
1950 throw new NullPointerException();
1951 return doPut(key, value, true);
1952 }
1953
1954 /**
1955 * {@inheritDoc}
1956 *
1957 * @throws ClassCastException if the specified key cannot be compared
1958 * with the keys currently in the map
1959 * @throws NullPointerException if the specified key is null
1960 */
1961 public boolean remove(Object key, Object value) {
1962 if (key == null)
1963 throw new NullPointerException();
1964 return value != null && doRemove(key, value) != null;
1965 }
1966
1967 /**
1968 * {@inheritDoc}
1969 *
1970 * @throws ClassCastException if the specified key cannot be compared
1971 * with the keys currently in the map
1972 * @throws NullPointerException if any of the arguments are null
1973 */
1974 public boolean replace(K key, V oldValue, V newValue) {
1975 if (key == null || oldValue == null || newValue == null)
1976 throw new NullPointerException();
1977 for (;;) {
1978 Node<K,V> n; Object v;
1979 if ((n = findNode(key)) == null)
1980 return false;
1981 if ((v = n.value) != null) {
1982 if (!oldValue.equals(v))
1983 return false;
1984 if (n.casValue(v, newValue))
1985 return true;
1986 }
1987 }
1988 }
1989
1990 /**
1991 * {@inheritDoc}
1992 *
1993 * @return the previous value associated with the specified key,
1994 * or {@code null} if there was no mapping for the key
1995 * @throws ClassCastException if the specified key cannot be compared
1996 * with the keys currently in the map
1997 * @throws NullPointerException if the specified key or value is null
1998 */
1999 public V replace(K key, V value) {
2000 if (key == null || value == null)
2001 throw new NullPointerException();
2002 for (;;) {
2003 Node<K,V> n; Object v;
2004 if ((n = findNode(key)) == null)
2005 return null;
2006 if ((v = n.value) != null && n.casValue(v, value)) {
2007 @SuppressWarnings("unchecked") V vv = (V)v;
2008 return vv;
2009 }
2010 }
2011 }
2012
2013 /* ------ SortedMap API methods ------ */
2014
2015 public Comparator<? super K> comparator() {
2016 return comparator;
2017 }
2018
2019 /**
2020 * @throws NoSuchElementException {@inheritDoc}
2021 */
2022 public K firstKey() {
2023 Node<K,V> n = findFirst();
2024 if (n == null)
2025 throw new NoSuchElementException();
2026 return n.key;
2027 }
2028
2029 /**
2030 * @throws NoSuchElementException {@inheritDoc}
2031 */
2032 public K lastKey() {
2033 Node<K,V> n = findLast();
2034 if (n == null)
2035 throw new NoSuchElementException();
2036 return n.key;
2037 }
2038
2039 /**
2040 * @throws ClassCastException {@inheritDoc}
2041 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2042 * @throws IllegalArgumentException {@inheritDoc}
2043 */
2044 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
2045 boolean fromInclusive,
2046 K toKey,
2047 boolean toInclusive) {
2048 if (fromKey == null || toKey == null)
2049 throw new NullPointerException();
2050 return new SubMap<K,V>
2051 (this, fromKey, fromInclusive, toKey, toInclusive, false);
2052 }
2053
2054 /**
2055 * @throws ClassCastException {@inheritDoc}
2056 * @throws NullPointerException if {@code toKey} is null
2057 * @throws IllegalArgumentException {@inheritDoc}
2058 */
2059 public ConcurrentNavigableMap<K,V> headMap(K toKey,
2060 boolean inclusive) {
2061 if (toKey == null)
2062 throw new NullPointerException();
2063 return new SubMap<K,V>
2064 (this, null, false, toKey, inclusive, false);
2065 }
2066
2067 /**
2068 * @throws ClassCastException {@inheritDoc}
2069 * @throws NullPointerException if {@code fromKey} is null
2070 * @throws IllegalArgumentException {@inheritDoc}
2071 */
2072 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2073 boolean inclusive) {
2074 if (fromKey == null)
2075 throw new NullPointerException();
2076 return new SubMap<K,V>
2077 (this, fromKey, inclusive, null, false, false);
2078 }
2079
2080 /**
2081 * @throws ClassCastException {@inheritDoc}
2082 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2083 * @throws IllegalArgumentException {@inheritDoc}
2084 */
2085 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2086 return subMap(fromKey, true, toKey, false);
2087 }
2088
2089 /**
2090 * @throws ClassCastException {@inheritDoc}
2091 * @throws NullPointerException if {@code toKey} is null
2092 * @throws IllegalArgumentException {@inheritDoc}
2093 */
2094 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2095 return headMap(toKey, false);
2096 }
2097
2098 /**
2099 * @throws ClassCastException {@inheritDoc}
2100 * @throws NullPointerException if {@code fromKey} is null
2101 * @throws IllegalArgumentException {@inheritDoc}
2102 */
2103 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2104 return tailMap(fromKey, true);
2105 }
2106
2107 /* ---------------- Relational operations -------------- */
2108
2109 /**
2110 * Returns a key-value mapping associated with the greatest key
2111 * strictly less than the given key, or {@code null} if there is
2112 * no such key. The returned entry does <em>not</em> support the
2113 * {@code Entry.setValue} method.
2114 *
2115 * @throws ClassCastException {@inheritDoc}
2116 * @throws NullPointerException if the specified key is null
2117 */
2118 public Map.Entry<K,V> lowerEntry(K key) {
2119 return getNear(key, LT);
2120 }
2121
2122 /**
2123 * @throws ClassCastException {@inheritDoc}
2124 * @throws NullPointerException if the specified key is null
2125 */
2126 public K lowerKey(K key) {
2127 Node<K,V> n = findNear(key, LT, comparator);
2128 return (n == null) ? null : n.key;
2129 }
2130
2131 /**
2132 * Returns a key-value mapping associated with the greatest key
2133 * less than or equal to the given key, or {@code null} if there
2134 * is no such key. The returned entry does <em>not</em> support
2135 * the {@code Entry.setValue} method.
2136 *
2137 * @param key the key
2138 * @throws ClassCastException {@inheritDoc}
2139 * @throws NullPointerException if the specified key is null
2140 */
2141 public Map.Entry<K,V> floorEntry(K key) {
2142 return getNear(key, LT|EQ);
2143 }
2144
2145 /**
2146 * @param key the key
2147 * @throws ClassCastException {@inheritDoc}
2148 * @throws NullPointerException if the specified key is null
2149 */
2150 public K floorKey(K key) {
2151 Node<K,V> n = findNear(key, LT|EQ, comparator);
2152 return (n == null) ? null : n.key;
2153 }
2154
2155 /**
2156 * Returns a key-value mapping associated with the least key
2157 * greater than or equal to the given key, or {@code null} if
2158 * there is no such entry. The returned entry does <em>not</em>
2159 * support the {@code Entry.setValue} method.
2160 *
2161 * @throws ClassCastException {@inheritDoc}
2162 * @throws NullPointerException if the specified key is null
2163 */
2164 public Map.Entry<K,V> ceilingEntry(K key) {
2165 return getNear(key, GT|EQ);
2166 }
2167
2168 /**
2169 * @throws ClassCastException {@inheritDoc}
2170 * @throws NullPointerException if the specified key is null
2171 */
2172 public K ceilingKey(K key) {
2173 Node<K,V> n = findNear(key, GT|EQ, comparator);
2174 return (n == null) ? null : n.key;
2175 }
2176
2177 /**
2178 * Returns a key-value mapping associated with the least key
2179 * strictly greater than the given key, or {@code null} if there
2180 * is no such key. The returned entry does <em>not</em> support
2181 * the {@code Entry.setValue} method.
2182 *
2183 * @param key the key
2184 * @throws ClassCastException {@inheritDoc}
2185 * @throws NullPointerException if the specified key is null
2186 */
2187 public Map.Entry<K,V> higherEntry(K key) {
2188 return getNear(key, GT);
2189 }
2190
2191 /**
2192 * @param key the key
2193 * @throws ClassCastException {@inheritDoc}
2194 * @throws NullPointerException if the specified key is null
2195 */
2196 public K higherKey(K key) {
2197 Node<K,V> n = findNear(key, GT, comparator);
2198 return (n == null) ? null : n.key;
2199 }
2200
2201 /**
2202 * Returns a key-value mapping associated with the least
2203 * key in this map, or {@code null} if the map is empty.
2204 * The returned entry does <em>not</em> support
2205 * the {@code Entry.setValue} method.
2206 */
2207 public Map.Entry<K,V> firstEntry() {
2208 for (;;) {
2209 Node<K,V> n = findFirst();
2210 if (n == null)
2211 return null;
2212 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2213 if (e != null)
2214 return e;
2215 }
2216 }
2217
2218 /**
2219 * Returns a key-value mapping associated with the greatest
2220 * key in this map, or {@code null} if the map is empty.
2221 * The returned entry does <em>not</em> support
2222 * the {@code Entry.setValue} method.
2223 */
2224 public Map.Entry<K,V> lastEntry() {
2225 for (;;) {
2226 Node<K,V> n = findLast();
2227 if (n == null)
2228 return null;
2229 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2230 if (e != null)
2231 return e;
2232 }
2233 }
2234
2235 /**
2236 * Removes and returns a key-value mapping associated with
2237 * the least key in this map, or {@code null} if the map is empty.
2238 * The returned entry does <em>not</em> support
2239 * the {@code Entry.setValue} method.
2240 */
2241 public Map.Entry<K,V> pollFirstEntry() {
2242 return doRemoveFirstEntry();
2243 }
2244
2245 /**
2246 * Removes and returns a key-value mapping associated with
2247 * the greatest key in this map, or {@code null} if the map is empty.
2248 * The returned entry does <em>not</em> support
2249 * the {@code Entry.setValue} method.
2250 */
2251 public Map.Entry<K,V> pollLastEntry() {
2252 return doRemoveLastEntry();
2253 }
2254
2255
2256 /* ---------------- Iterators -------------- */
2257
2258 /**
2259 * Base of iterator classes:
2260 */
2261 abstract class Iter<T> implements Iterator<T> {
2262 /** the last node returned by next() */
2263 Node<K,V> lastReturned;
2264 /** the next node to return from next(); */
2265 Node<K,V> next;
2266 /** Cache of next value field to maintain weak consistency */
2267 V nextValue;
2268
2269 /** Initializes ascending iterator for entire range. */
2270 Iter() {
2271 while ((next = findFirst()) != null) {
2272 Object x = next.value;
2273 if (x != null && x != next) {
2274 @SuppressWarnings("unchecked") V vv = (V)x;
2275 nextValue = vv;
2276 break;
2277 }
2278 }
2279 }
2280
2281 public final boolean hasNext() {
2282 return next != null;
2283 }
2284
2285 /** Advances next to higher entry. */
2286 final void advance() {
2287 if (next == null)
2288 throw new NoSuchElementException();
2289 lastReturned = next;
2290 while ((next = next.next) != null) {
2291 Object x = next.value;
2292 if (x != null && x != next) {
2293 @SuppressWarnings("unchecked") V vv = (V)x;
2294 nextValue = vv;
2295 break;
2296 }
2297 }
2298 }
2299
2300 public void remove() {
2301 Node<K,V> l = lastReturned;
2302 if (l == null)
2303 throw new IllegalStateException();
2304 // It would not be worth all of the overhead to directly
2305 // unlink from here. Using remove is fast enough.
2306 ConcurrentSkipListMap.this.remove(l.key);
2307 lastReturned = null;
2308 }
2309
2310 }
2311
2312 final class ValueIterator extends Iter<V> {
2313 public V next() {
2314 V v = nextValue;
2315 advance();
2316 return v;
2317 }
2318 }
2319
2320 final class KeyIterator extends Iter<K> {
2321 public K next() {
2322 Node<K,V> n = next;
2323 advance();
2324 return n.key;
2325 }
2326 }
2327
2328 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2329 public Map.Entry<K,V> next() {
2330 Node<K,V> n = next;
2331 V v = nextValue;
2332 advance();
2333 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2334 }
2335 }
2336
2337 /* ---------------- View Classes -------------- */
2338
2339 /*
2340 * View classes are static, delegating to a ConcurrentNavigableMap
2341 * to allow use by SubMaps, which outweighs the ugliness of
2342 * needing type-tests for Iterator methods.
2343 */
2344
2345 static final <E> List<E> toList(Collection<E> c) {
2346 // Using size() here would be a pessimization.
2347 ArrayList<E> list = new ArrayList<E>();
2348 for (E e : c)
2349 list.add(e);
2350 return list;
2351 }
2352
2353 static final class KeySet<K,V>
2354 extends AbstractSet<K> implements NavigableSet<K> {
2355 final ConcurrentNavigableMap<K,V> m;
2356 KeySet(ConcurrentNavigableMap<K,V> map) { m = map; }
2357 public int size() { return m.size(); }
2358 public boolean isEmpty() { return m.isEmpty(); }
2359 public boolean contains(Object o) { return m.containsKey(o); }
2360 public boolean remove(Object o) { return m.remove(o) != null; }
2361 public void clear() { m.clear(); }
2362 public K lower(K e) { return m.lowerKey(e); }
2363 public K floor(K e) { return m.floorKey(e); }
2364 public K ceiling(K e) { return m.ceilingKey(e); }
2365 public K higher(K e) { return m.higherKey(e); }
2366 public Comparator<? super K> comparator() { return m.comparator(); }
2367 public K first() { return m.firstKey(); }
2368 public K last() { return m.lastKey(); }
2369 public K pollFirst() {
2370 Map.Entry<K,V> e = m.pollFirstEntry();
2371 return (e == null) ? null : e.getKey();
2372 }
2373 public K pollLast() {
2374 Map.Entry<K,V> e = m.pollLastEntry();
2375 return (e == null) ? null : e.getKey();
2376 }
2377 public Iterator<K> iterator() {
2378 return (m instanceof ConcurrentSkipListMap)
2379 ? ((ConcurrentSkipListMap<K,V>)m).new KeyIterator()
2380 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2381 }
2382 public boolean equals(Object o) {
2383 if (o == this)
2384 return true;
2385 if (!(o instanceof Set))
2386 return false;
2387 Collection<?> c = (Collection<?>) o;
2388 try {
2389 return containsAll(c) && c.containsAll(this);
2390 } catch (ClassCastException unused) {
2391 return false;
2392 } catch (NullPointerException unused) {
2393 return false;
2394 }
2395 }
2396 public Object[] toArray() { return toList(this).toArray(); }
2397 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2398 public Iterator<K> descendingIterator() {
2399 return descendingSet().iterator();
2400 }
2401 public NavigableSet<K> subSet(K fromElement,
2402 boolean fromInclusive,
2403 K toElement,
2404 boolean toInclusive) {
2405 return new KeySet<>(m.subMap(fromElement, fromInclusive,
2406 toElement, toInclusive));
2407 }
2408 public NavigableSet<K> headSet(K toElement, boolean inclusive) {
2409 return new KeySet<>(m.headMap(toElement, inclusive));
2410 }
2411 public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
2412 return new KeySet<>(m.tailMap(fromElement, inclusive));
2413 }
2414 public NavigableSet<K> subSet(K fromElement, K toElement) {
2415 return subSet(fromElement, true, toElement, false);
2416 }
2417 public NavigableSet<K> headSet(K toElement) {
2418 return headSet(toElement, false);
2419 }
2420 public NavigableSet<K> tailSet(K fromElement) {
2421 return tailSet(fromElement, true);
2422 }
2423 public NavigableSet<K> descendingSet() {
2424 return new KeySet<>(m.descendingMap());
2425 }
2426
2427 public Spliterator<K> spliterator() {
2428 return (m instanceof ConcurrentSkipListMap)
2429 ? ((ConcurrentSkipListMap<K,V>)m).keySpliterator()
2430 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2431 }
2432 }
2433
2434 static final class Values<K,V> extends AbstractCollection<V> {
2435 final ConcurrentNavigableMap<K,V> m;
2436 Values(ConcurrentNavigableMap<K,V> map) {
2437 m = map;
2438 }
2439 public Iterator<V> iterator() {
2440 return (m instanceof ConcurrentSkipListMap)
2441 ? ((ConcurrentSkipListMap<K,V>)m).new ValueIterator()
2442 : ((SubMap<K,V>)m).new SubMapValueIterator();
2443 }
2444 public int size() { return m.size(); }
2445 public boolean isEmpty() { return m.isEmpty(); }
2446 public boolean contains(Object o) { return m.containsValue(o); }
2447 public void clear() { m.clear(); }
2448 public Object[] toArray() { return toList(this).toArray(); }
2449 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2450
2451 public Spliterator<V> spliterator() {
2452 return (m instanceof ConcurrentSkipListMap)
2453 ? ((ConcurrentSkipListMap<K,V>)m).valueSpliterator()
2454 : ((SubMap<K,V>)m).new SubMapValueIterator();
2455 }
2456
2457 public boolean removeIf(Predicate<? super V> filter) {
2458 if (filter == null) throw new NullPointerException();
2459 if (m instanceof ConcurrentSkipListMap)
2460 return ((ConcurrentSkipListMap<K,V>)m).removeValueIf(filter);
2461 // else use iterator
2462 Iterator<Map.Entry<K,V>> it =
2463 ((SubMap<K,V>)m).new SubMapEntryIterator();
2464 boolean removed = false;
2465 while (it.hasNext()) {
2466 Map.Entry<K,V> e = it.next();
2467 V v = e.getValue();
2468 if (filter.test(v) && m.remove(e.getKey(), v))
2469 removed = true;
2470 }
2471 return removed;
2472 }
2473 }
2474
2475 static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> {
2476 final ConcurrentNavigableMap<K,V> m;
2477 EntrySet(ConcurrentNavigableMap<K,V> map) {
2478 m = map;
2479 }
2480 public Iterator<Map.Entry<K,V>> iterator() {
2481 return (m instanceof ConcurrentSkipListMap)
2482 ? ((ConcurrentSkipListMap<K,V>)m).new EntryIterator()
2483 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2484 }
2485
2486 public boolean contains(Object o) {
2487 if (!(o instanceof Map.Entry))
2488 return false;
2489 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2490 V v = m.get(e.getKey());
2491 return v != null && v.equals(e.getValue());
2492 }
2493 public boolean remove(Object o) {
2494 if (!(o instanceof Map.Entry))
2495 return false;
2496 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2497 return m.remove(e.getKey(),
2498 e.getValue());
2499 }
2500 public boolean isEmpty() {
2501 return m.isEmpty();
2502 }
2503 public int size() {
2504 return m.size();
2505 }
2506 public void clear() {
2507 m.clear();
2508 }
2509 public boolean equals(Object o) {
2510 if (o == this)
2511 return true;
2512 if (!(o instanceof Set))
2513 return false;
2514 Collection<?> c = (Collection<?>) o;
2515 try {
2516 return containsAll(c) && c.containsAll(this);
2517 } catch (ClassCastException unused) {
2518 return false;
2519 } catch (NullPointerException unused) {
2520 return false;
2521 }
2522 }
2523 public Object[] toArray() { return toList(this).toArray(); }
2524 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2525
2526 public Spliterator<Map.Entry<K,V>> spliterator() {
2527 return (m instanceof ConcurrentSkipListMap)
2528 ? ((ConcurrentSkipListMap<K,V>)m).entrySpliterator()
2529 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2530 }
2531 public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
2532 if (filter == null) throw new NullPointerException();
2533 if (m instanceof ConcurrentSkipListMap)
2534 return ((ConcurrentSkipListMap<K,V>)m).removeEntryIf(filter);
2535 // else use iterator
2536 Iterator<Map.Entry<K,V>> it =
2537 ((SubMap<K,V>)m).new SubMapEntryIterator();
2538 boolean removed = false;
2539 while (it.hasNext()) {
2540 Map.Entry<K,V> e = it.next();
2541 if (filter.test(e) && m.remove(e.getKey(), e.getValue()))
2542 removed = true;
2543 }
2544 return removed;
2545 }
2546 }
2547
2548 /**
2549 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2550 * represent a subrange of mappings of their underlying maps.
2551 * Instances of this class support all methods of their underlying
2552 * maps, differing in that mappings outside their range are ignored,
2553 * and attempts to add mappings outside their ranges result in {@link
2554 * IllegalArgumentException}. Instances of this class are constructed
2555 * only using the {@code subMap}, {@code headMap}, and {@code tailMap}
2556 * methods of their underlying maps.
2557 *
2558 * @serial include
2559 */
2560 static final class SubMap<K,V> extends AbstractMap<K,V>
2561 implements ConcurrentNavigableMap<K,V>, Serializable {
2562 private static final long serialVersionUID = -7647078645895051609L;
2563
2564 /** Underlying map */
2565 final ConcurrentSkipListMap<K,V> m;
2566 /** lower bound key, or null if from start */
2567 private final K lo;
2568 /** upper bound key, or null if to end */
2569 private final K hi;
2570 /** inclusion flag for lo */
2571 private final boolean loInclusive;
2572 /** inclusion flag for hi */
2573 private final boolean hiInclusive;
2574 /** direction */
2575 final boolean isDescending;
2576
2577 // Lazily initialized view holders
2578 private transient KeySet<K,V> keySetView;
2579 private transient Values<K,V> valuesView;
2580 private transient EntrySet<K,V> entrySetView;
2581
2582 /**
2583 * Creates a new submap, initializing all fields.
2584 */
2585 SubMap(ConcurrentSkipListMap<K,V> map,
2586 K fromKey, boolean fromInclusive,
2587 K toKey, boolean toInclusive,
2588 boolean isDescending) {
2589 Comparator<? super K> cmp = map.comparator;
2590 if (fromKey != null && toKey != null &&
2591 cpr(cmp, fromKey, toKey) > 0)
2592 throw new IllegalArgumentException("inconsistent range");
2593 this.m = map;
2594 this.lo = fromKey;
2595 this.hi = toKey;
2596 this.loInclusive = fromInclusive;
2597 this.hiInclusive = toInclusive;
2598 this.isDescending = isDescending;
2599 }
2600
2601 /* ---------------- Utilities -------------- */
2602
2603 boolean tooLow(Object key, Comparator<? super K> cmp) {
2604 int c;
2605 return (lo != null && ((c = cpr(cmp, key, lo)) < 0 ||
2606 (c == 0 && !loInclusive)));
2607 }
2608
2609 boolean tooHigh(Object key, Comparator<? super K> cmp) {
2610 int c;
2611 return (hi != null && ((c = cpr(cmp, key, hi)) > 0 ||
2612 (c == 0 && !hiInclusive)));
2613 }
2614
2615 boolean inBounds(Object key, Comparator<? super K> cmp) {
2616 return !tooLow(key, cmp) && !tooHigh(key, cmp);
2617 }
2618
2619 void checkKeyBounds(K key, Comparator<? super K> cmp) {
2620 if (key == null)
2621 throw new NullPointerException();
2622 if (!inBounds(key, cmp))
2623 throw new IllegalArgumentException("key out of range");
2624 }
2625
2626 /**
2627 * Returns true if node key is less than upper bound of range.
2628 */
2629 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n,
2630 Comparator<? super K> cmp) {
2631 if (n == null)
2632 return false;
2633 if (hi == null)
2634 return true;
2635 K k = n.key;
2636 if (k == null) // pass by markers and headers
2637 return true;
2638 int c = cpr(cmp, k, hi);
2639 if (c > 0 || (c == 0 && !hiInclusive))
2640 return false;
2641 return true;
2642 }
2643
2644 /**
2645 * Returns lowest node. This node might not be in range, so
2646 * most usages need to check bounds.
2647 */
2648 ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) {
2649 if (lo == null)
2650 return m.findFirst();
2651 else if (loInclusive)
2652 return m.findNear(lo, GT|EQ, cmp);
2653 else
2654 return m.findNear(lo, GT, cmp);
2655 }
2656
2657 /**
2658 * Returns highest node. This node might not be in range, so
2659 * most usages need to check bounds.
2660 */
2661 ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) {
2662 if (hi == null)
2663 return m.findLast();
2664 else if (hiInclusive)
2665 return m.findNear(hi, LT|EQ, cmp);
2666 else
2667 return m.findNear(hi, LT, cmp);
2668 }
2669
2670 /**
2671 * Returns lowest absolute key (ignoring directionality).
2672 */
2673 K lowestKey() {
2674 Comparator<? super K> cmp = m.comparator;
2675 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2676 if (isBeforeEnd(n, cmp))
2677 return n.key;
2678 else
2679 throw new NoSuchElementException();
2680 }
2681
2682 /**
2683 * Returns highest absolute key (ignoring directionality).
2684 */
2685 K highestKey() {
2686 Comparator<? super K> cmp = m.comparator;
2687 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2688 if (n != null) {
2689 K last = n.key;
2690 if (inBounds(last, cmp))
2691 return last;
2692 }
2693 throw new NoSuchElementException();
2694 }
2695
2696 Map.Entry<K,V> lowestEntry() {
2697 Comparator<? super K> cmp = m.comparator;
2698 for (;;) {
2699 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2700 if (!isBeforeEnd(n, cmp))
2701 return null;
2702 Map.Entry<K,V> e = n.createSnapshot();
2703 if (e != null)
2704 return e;
2705 }
2706 }
2707
2708 Map.Entry<K,V> highestEntry() {
2709 Comparator<? super K> cmp = m.comparator;
2710 for (;;) {
2711 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2712 if (n == null || !inBounds(n.key, cmp))
2713 return null;
2714 Map.Entry<K,V> e = n.createSnapshot();
2715 if (e != null)
2716 return e;
2717 }
2718 }
2719
2720 Map.Entry<K,V> removeLowest() {
2721 Comparator<? super K> cmp = m.comparator;
2722 for (;;) {
2723 Node<K,V> n = loNode(cmp);
2724 if (n == null)
2725 return null;
2726 K k = n.key;
2727 if (!inBounds(k, cmp))
2728 return null;
2729 V v = m.doRemove(k, null);
2730 if (v != null)
2731 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2732 }
2733 }
2734
2735 Map.Entry<K,V> removeHighest() {
2736 Comparator<? super K> cmp = m.comparator;
2737 for (;;) {
2738 Node<K,V> n = hiNode(cmp);
2739 if (n == null)
2740 return null;
2741 K k = n.key;
2742 if (!inBounds(k, cmp))
2743 return null;
2744 V v = m.doRemove(k, null);
2745 if (v != null)
2746 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2747 }
2748 }
2749
2750 /**
2751 * Submap version of ConcurrentSkipListMap.getNearEntry.
2752 */
2753 Map.Entry<K,V> getNearEntry(K key, int rel) {
2754 Comparator<? super K> cmp = m.comparator;
2755 if (isDescending) { // adjust relation for direction
2756 if ((rel & LT) == 0)
2757 rel |= LT;
2758 else
2759 rel &= ~LT;
2760 }
2761 if (tooLow(key, cmp))
2762 return ((rel & LT) != 0) ? null : lowestEntry();
2763 if (tooHigh(key, cmp))
2764 return ((rel & LT) != 0) ? highestEntry() : null;
2765 for (;;) {
2766 Node<K,V> n = m.findNear(key, rel, cmp);
2767 if (n == null || !inBounds(n.key, cmp))
2768 return null;
2769 K k = n.key;
2770 V v = n.getValidValue();
2771 if (v != null)
2772 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2773 }
2774 }
2775
2776 // Almost the same as getNearEntry, except for keys
2777 K getNearKey(K key, int rel) {
2778 Comparator<? super K> cmp = m.comparator;
2779 if (isDescending) { // adjust relation for direction
2780 if ((rel & LT) == 0)
2781 rel |= LT;
2782 else
2783 rel &= ~LT;
2784 }
2785 if (tooLow(key, cmp)) {
2786 if ((rel & LT) == 0) {
2787 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2788 if (isBeforeEnd(n, cmp))
2789 return n.key;
2790 }
2791 return null;
2792 }
2793 if (tooHigh(key, cmp)) {
2794 if ((rel & LT) != 0) {
2795 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2796 if (n != null) {
2797 K last = n.key;
2798 if (inBounds(last, cmp))
2799 return last;
2800 }
2801 }
2802 return null;
2803 }
2804 for (;;) {
2805 Node<K,V> n = m.findNear(key, rel, cmp);
2806 if (n == null || !inBounds(n.key, cmp))
2807 return null;
2808 K k = n.key;
2809 V v = n.getValidValue();
2810 if (v != null)
2811 return k;
2812 }
2813 }
2814
2815 /* ---------------- Map API methods -------------- */
2816
2817 public boolean containsKey(Object key) {
2818 if (key == null) throw new NullPointerException();
2819 return inBounds(key, m.comparator) && m.containsKey(key);
2820 }
2821
2822 public V get(Object key) {
2823 if (key == null) throw new NullPointerException();
2824 return (!inBounds(key, m.comparator)) ? null : m.get(key);
2825 }
2826
2827 public V put(K key, V value) {
2828 checkKeyBounds(key, m.comparator);
2829 return m.put(key, value);
2830 }
2831
2832 public V remove(Object key) {
2833 return (!inBounds(key, m.comparator)) ? null : m.remove(key);
2834 }
2835
2836 public int size() {
2837 Comparator<? super K> cmp = m.comparator;
2838 long count = 0;
2839 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2840 isBeforeEnd(n, cmp);
2841 n = n.next) {
2842 if (n.getValidValue() != null)
2843 ++count;
2844 }
2845 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2846 }
2847
2848 public boolean isEmpty() {
2849 Comparator<? super K> cmp = m.comparator;
2850 return !isBeforeEnd(loNode(cmp), cmp);
2851 }
2852
2853 public boolean containsValue(Object value) {
2854 if (value == null)
2855 throw new NullPointerException();
2856 Comparator<? super K> cmp = m.comparator;
2857 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2858 isBeforeEnd(n, cmp);
2859 n = n.next) {
2860 V v = n.getValidValue();
2861 if (v != null && value.equals(v))
2862 return true;
2863 }
2864 return false;
2865 }
2866
2867 public void clear() {
2868 Comparator<? super K> cmp = m.comparator;
2869 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2870 isBeforeEnd(n, cmp);
2871 n = n.next) {
2872 if (n.getValidValue() != null)
2873 m.remove(n.key);
2874 }
2875 }
2876
2877 /* ---------------- ConcurrentMap API methods -------------- */
2878
2879 public V putIfAbsent(K key, V value) {
2880 checkKeyBounds(key, m.comparator);
2881 return m.putIfAbsent(key, value);
2882 }
2883
2884 public boolean remove(Object key, Object value) {
2885 return inBounds(key, m.comparator) && m.remove(key, value);
2886 }
2887
2888 public boolean replace(K key, V oldValue, V newValue) {
2889 checkKeyBounds(key, m.comparator);
2890 return m.replace(key, oldValue, newValue);
2891 }
2892
2893 public V replace(K key, V value) {
2894 checkKeyBounds(key, m.comparator);
2895 return m.replace(key, value);
2896 }
2897
2898 /* ---------------- SortedMap API methods -------------- */
2899
2900 public Comparator<? super K> comparator() {
2901 Comparator<? super K> cmp = m.comparator();
2902 if (isDescending)
2903 return Collections.reverseOrder(cmp);
2904 else
2905 return cmp;
2906 }
2907
2908 /**
2909 * Utility to create submaps, where given bounds override
2910 * unbounded(null) ones and/or are checked against bounded ones.
2911 */
2912 SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive,
2913 K toKey, boolean toInclusive) {
2914 Comparator<? super K> cmp = m.comparator;
2915 if (isDescending) { // flip senses
2916 K tk = fromKey;
2917 fromKey = toKey;
2918 toKey = tk;
2919 boolean ti = fromInclusive;
2920 fromInclusive = toInclusive;
2921 toInclusive = ti;
2922 }
2923 if (lo != null) {
2924 if (fromKey == null) {
2925 fromKey = lo;
2926 fromInclusive = loInclusive;
2927 }
2928 else {
2929 int c = cpr(cmp, fromKey, lo);
2930 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2931 throw new IllegalArgumentException("key out of range");
2932 }
2933 }
2934 if (hi != null) {
2935 if (toKey == null) {
2936 toKey = hi;
2937 toInclusive = hiInclusive;
2938 }
2939 else {
2940 int c = cpr(cmp, toKey, hi);
2941 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2942 throw new IllegalArgumentException("key out of range");
2943 }
2944 }
2945 return new SubMap<K,V>(m, fromKey, fromInclusive,
2946 toKey, toInclusive, isDescending);
2947 }
2948
2949 public SubMap<K,V> subMap(K fromKey, boolean fromInclusive,
2950 K toKey, boolean toInclusive) {
2951 if (fromKey == null || toKey == null)
2952 throw new NullPointerException();
2953 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2954 }
2955
2956 public SubMap<K,V> headMap(K toKey, boolean inclusive) {
2957 if (toKey == null)
2958 throw new NullPointerException();
2959 return newSubMap(null, false, toKey, inclusive);
2960 }
2961
2962 public SubMap<K,V> tailMap(K fromKey, boolean inclusive) {
2963 if (fromKey == null)
2964 throw new NullPointerException();
2965 return newSubMap(fromKey, inclusive, null, false);
2966 }
2967
2968 public SubMap<K,V> subMap(K fromKey, K toKey) {
2969 return subMap(fromKey, true, toKey, false);
2970 }
2971
2972 public SubMap<K,V> headMap(K toKey) {
2973 return headMap(toKey, false);
2974 }
2975
2976 public SubMap<K,V> tailMap(K fromKey) {
2977 return tailMap(fromKey, true);
2978 }
2979
2980 public SubMap<K,V> descendingMap() {
2981 return new SubMap<K,V>(m, lo, loInclusive,
2982 hi, hiInclusive, !isDescending);
2983 }
2984
2985 /* ---------------- Relational methods -------------- */
2986
2987 public Map.Entry<K,V> ceilingEntry(K key) {
2988 return getNearEntry(key, GT|EQ);
2989 }
2990
2991 public K ceilingKey(K key) {
2992 return getNearKey(key, GT|EQ);
2993 }
2994
2995 public Map.Entry<K,V> lowerEntry(K key) {
2996 return getNearEntry(key, LT);
2997 }
2998
2999 public K lowerKey(K key) {
3000 return getNearKey(key, LT);
3001 }
3002
3003 public Map.Entry<K,V> floorEntry(K key) {
3004 return getNearEntry(key, LT|EQ);
3005 }
3006
3007 public K floorKey(K key) {
3008 return getNearKey(key, LT|EQ);
3009 }
3010
3011 public Map.Entry<K,V> higherEntry(K key) {
3012 return getNearEntry(key, GT);
3013 }
3014
3015 public K higherKey(K key) {
3016 return getNearKey(key, GT);
3017 }
3018
3019 public K firstKey() {
3020 return isDescending ? highestKey() : lowestKey();
3021 }
3022
3023 public K lastKey() {
3024 return isDescending ? lowestKey() : highestKey();
3025 }
3026
3027 public Map.Entry<K,V> firstEntry() {
3028 return isDescending ? highestEntry() : lowestEntry();
3029 }
3030
3031 public Map.Entry<K,V> lastEntry() {
3032 return isDescending ? lowestEntry() : highestEntry();
3033 }
3034
3035 public Map.Entry<K,V> pollFirstEntry() {
3036 return isDescending ? removeHighest() : removeLowest();
3037 }
3038
3039 public Map.Entry<K,V> pollLastEntry() {
3040 return isDescending ? removeLowest() : removeHighest();
3041 }
3042
3043 /* ---------------- Submap Views -------------- */
3044
3045 public NavigableSet<K> keySet() {
3046 KeySet<K,V> ks;
3047 if ((ks = keySetView) != null) return ks;
3048 return keySetView = new KeySet<>(this);
3049 }
3050
3051 public NavigableSet<K> navigableKeySet() {
3052 KeySet<K,V> ks;
3053 if ((ks = keySetView) != null) return ks;
3054 return keySetView = new KeySet<>(this);
3055 }
3056
3057 public Collection<V> values() {
3058 Values<K,V> vs;
3059 if ((vs = valuesView) != null) return vs;
3060 return valuesView = new Values<>(this);
3061 }
3062
3063 public Set<Map.Entry<K,V>> entrySet() {
3064 EntrySet<K,V> es;
3065 if ((es = entrySetView) != null) return es;
3066 return entrySetView = new EntrySet<K,V>(this);
3067 }
3068
3069 public NavigableSet<K> descendingKeySet() {
3070 return descendingMap().navigableKeySet();
3071 }
3072
3073 /**
3074 * Variant of main Iter class to traverse through submaps.
3075 * Also serves as back-up Spliterator for views.
3076 */
3077 abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> {
3078 /** the last node returned by next() */
3079 Node<K,V> lastReturned;
3080 /** the next node to return from next(); */
3081 Node<K,V> next;
3082 /** Cache of next value field to maintain weak consistency */
3083 V nextValue;
3084
3085 SubMapIter() {
3086 Comparator<? super K> cmp = m.comparator;
3087 for (;;) {
3088 next = isDescending ? hiNode(cmp) : loNode(cmp);
3089 if (next == null)
3090 break;
3091 Object x = next.value;
3092 if (x != null && x != next) {
3093 if (! inBounds(next.key, cmp))
3094 next = null;
3095 else {
3096 @SuppressWarnings("unchecked") V vv = (V)x;
3097 nextValue = vv;
3098 }
3099 break;
3100 }
3101 }
3102 }
3103
3104 public final boolean hasNext() {
3105 return next != null;
3106 }
3107
3108 final void advance() {
3109 if (next == null)
3110 throw new NoSuchElementException();
3111 lastReturned = next;
3112 if (isDescending)
3113 descend();
3114 else
3115 ascend();
3116 }
3117
3118 private void ascend() {
3119 Comparator<? super K> cmp = m.comparator;
3120 for (;;) {
3121 next = next.next;
3122 if (next == null)
3123 break;
3124 Object x = next.value;
3125 if (x != null && x != next) {
3126 if (tooHigh(next.key, cmp))
3127 next = null;
3128 else {
3129 @SuppressWarnings("unchecked") V vv = (V)x;
3130 nextValue = vv;
3131 }
3132 break;
3133 }
3134 }
3135 }
3136
3137 private void descend() {
3138 Comparator<? super K> cmp = m.comparator;
3139 for (;;) {
3140 next = m.findNear(lastReturned.key, LT, cmp);
3141 if (next == null)
3142 break;
3143 Object x = next.value;
3144 if (x != null && x != next) {
3145 if (tooLow(next.key, cmp))
3146 next = null;
3147 else {
3148 @SuppressWarnings("unchecked") V vv = (V)x;
3149 nextValue = vv;
3150 }
3151 break;
3152 }
3153 }
3154 }
3155
3156 public void remove() {
3157 Node<K,V> l = lastReturned;
3158 if (l == null)
3159 throw new IllegalStateException();
3160 m.remove(l.key);
3161 lastReturned = null;
3162 }
3163
3164 public Spliterator<T> trySplit() {
3165 return null;
3166 }
3167
3168 public boolean tryAdvance(Consumer<? super T> action) {
3169 if (hasNext()) {
3170 action.accept(next());
3171 return true;
3172 }
3173 return false;
3174 }
3175
3176 public void forEachRemaining(Consumer<? super T> action) {
3177 while (hasNext())
3178 action.accept(next());
3179 }
3180
3181 public long estimateSize() {
3182 return Long.MAX_VALUE;
3183 }
3184
3185 }
3186
3187 final class SubMapValueIterator extends SubMapIter<V> {
3188 public V next() {
3189 V v = nextValue;
3190 advance();
3191 return v;
3192 }
3193 public int characteristics() {
3194 return 0;
3195 }
3196 }
3197
3198 final class SubMapKeyIterator extends SubMapIter<K> {
3199 public K next() {
3200 Node<K,V> n = next;
3201 advance();
3202 return n.key;
3203 }
3204 public int characteristics() {
3205 return Spliterator.DISTINCT | Spliterator.ORDERED |
3206 Spliterator.SORTED;
3207 }
3208 public final Comparator<? super K> getComparator() {
3209 return SubMap.this.comparator();
3210 }
3211 }
3212
3213 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3214 public Map.Entry<K,V> next() {
3215 Node<K,V> n = next;
3216 V v = nextValue;
3217 advance();
3218 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3219 }
3220 public int characteristics() {
3221 return Spliterator.DISTINCT;
3222 }
3223 }
3224 }
3225
3226 // default Map method overrides
3227
3228 public void forEach(BiConsumer<? super K, ? super V> action) {
3229 if (action == null) throw new NullPointerException();
3230 V v;
3231 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3232 if ((v = n.getValidValue()) != null)
3233 action.accept(n.key, v);
3234 }
3235 }
3236
3237 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3238 if (function == null) throw new NullPointerException();
3239 V v;
3240 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3241 while ((v = n.getValidValue()) != null) {
3242 V r = function.apply(n.key, v);
3243 if (r == null) throw new NullPointerException();
3244 if (n.casValue(v, r))
3245 break;
3246 }
3247 }
3248 }
3249
3250 /**
3251 * Helper method for EntrySet.removeIf.
3252 */
3253 boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
3254 if (function == null) throw new NullPointerException();
3255 boolean removed = false;
3256 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3257 V v;
3258 if ((v = n.getValidValue()) != null) {
3259 K k = n.key;
3260 Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
3261 if (function.test(e) && remove(k, v))
3262 removed = true;
3263 }
3264 }
3265 return removed;
3266 }
3267
3268 /**
3269 * Helper method for Values.removeIf.
3270 */
3271 boolean removeValueIf(Predicate<? super V> function) {
3272 if (function == null) throw new NullPointerException();
3273 boolean removed = false;
3274 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3275 V v;
3276 if ((v = n.getValidValue()) != null) {
3277 K k = n.key;
3278 if (function.test(v) && remove(k, v))
3279 removed = true;
3280 }
3281 }
3282 return removed;
3283 }
3284
3285 /**
3286 * Base class providing common structure for Spliterators.
3287 * (Although not all that much common functionality; as usual for
3288 * view classes, details annoyingly vary in key, value, and entry
3289 * subclasses in ways that are not worth abstracting out for
3290 * internal classes.)
3291 *
3292 * The basic split strategy is to recursively descend from top
3293 * level, row by row, descending to next row when either split
3294 * off, or the end of row is encountered. Control of the number of
3295 * splits relies on some statistical estimation: The expected
3296 * remaining number of elements of a skip list when advancing
3297 * either across or down decreases by about 25%. To make this
3298 * observation useful, we need to know initial size, which we
3299 * don't. But we can just use Integer.MAX_VALUE so that we
3300 * don't prematurely zero out while splitting.
3301 */
3302 abstract static class CSLMSpliterator<K,V> {
3303 final Comparator<? super K> comparator;
3304 final K fence; // exclusive upper bound for keys, or null if to end
3305 Index<K,V> row; // the level to split out
3306 Node<K,V> current; // current traversal node; initialize at origin
3307 int est; // pseudo-size estimate
3308 CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3309 Node<K,V> origin, K fence, int est) {
3310 this.comparator = comparator; this.row = row;
3311 this.current = origin; this.fence = fence; this.est = est;
3312 }
3313
3314 public final long estimateSize() { return (long)est; }
3315 }
3316
3317 static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
3318 implements Spliterator<K> {
3319 KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3320 Node<K,V> origin, K fence, int est) {
3321 super(comparator, row, origin, fence, est);
3322 }
3323
3324 public KeySpliterator<K,V> trySplit() {
3325 Node<K,V> e; K ek;
3326 Comparator<? super K> cmp = comparator;
3327 K f = fence;
3328 if ((e = current) != null && (ek = e.key) != null) {
3329 for (Index<K,V> q = row; q != null; q = row = q.down) {
3330 Index<K,V> s; Node<K,V> b, n; K sk;
3331 if ((s = q.right) != null && (b = s.node) != null &&
3332 (n = b.next) != null && n.value != null &&
3333 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3334 (f == null || cpr(cmp, sk, f) < 0)) {
3335 current = n;
3336 Index<K,V> r = q.down;
3337 row = (s.right != null) ? s : s.down;
3338 est -= est >>> 2;
3339 return new KeySpliterator<K,V>(cmp, r, e, sk, est);
3340 }
3341 }
3342 }
3343 return null;
3344 }
3345
3346 public void forEachRemaining(Consumer<? super K> action) {
3347 if (action == null) throw new NullPointerException();
3348 Comparator<? super K> cmp = comparator;
3349 K f = fence;
3350 Node<K,V> e = current;
3351 current = null;
3352 for (; e != null; e = e.next) {
3353 K k; Object v;
3354 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3355 break;
3356 if ((v = e.value) != null && v != e)
3357 action.accept(k);
3358 }
3359 }
3360
3361 public boolean tryAdvance(Consumer<? super K> action) {
3362 if (action == null) throw new NullPointerException();
3363 Comparator<? super K> cmp = comparator;
3364 K f = fence;
3365 Node<K,V> e = current;
3366 for (; e != null; e = e.next) {
3367 K k; Object v;
3368 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3369 e = null;
3370 break;
3371 }
3372 if ((v = e.value) != null && v != e) {
3373 current = e.next;
3374 action.accept(k);
3375 return true;
3376 }
3377 }
3378 current = e;
3379 return false;
3380 }
3381
3382 public int characteristics() {
3383 return Spliterator.DISTINCT | Spliterator.SORTED |
3384 Spliterator.ORDERED | Spliterator.CONCURRENT |
3385 Spliterator.NONNULL;
3386 }
3387
3388 public final Comparator<? super K> getComparator() {
3389 return comparator;
3390 }
3391 }
3392 // factory method for KeySpliterator
3393 final KeySpliterator<K,V> keySpliterator() {
3394 Comparator<? super K> cmp = comparator;
3395 for (;;) { // ensure h corresponds to origin p
3396 HeadIndex<K,V> h; Node<K,V> p;
3397 Node<K,V> b = (h = head).node;
3398 if ((p = b.next) == null || p.value != null)
3399 return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3400 0 : Integer.MAX_VALUE);
3401 p.helpDelete(b, p.next);
3402 }
3403 }
3404
3405 static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
3406 implements Spliterator<V> {
3407 ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3408 Node<K,V> origin, K fence, int est) {
3409 super(comparator, row, origin, fence, est);
3410 }
3411
3412 public ValueSpliterator<K,V> trySplit() {
3413 Node<K,V> e; K ek;
3414 Comparator<? super K> cmp = comparator;
3415 K f = fence;
3416 if ((e = current) != null && (ek = e.key) != null) {
3417 for (Index<K,V> q = row; q != null; q = row = q.down) {
3418 Index<K,V> s; Node<K,V> b, n; K sk;
3419 if ((s = q.right) != null && (b = s.node) != null &&
3420 (n = b.next) != null && n.value != null &&
3421 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3422 (f == null || cpr(cmp, sk, f) < 0)) {
3423 current = n;
3424 Index<K,V> r = q.down;
3425 row = (s.right != null) ? s : s.down;
3426 est -= est >>> 2;
3427 return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
3428 }
3429 }
3430 }
3431 return null;
3432 }
3433
3434 public void forEachRemaining(Consumer<? super V> action) {
3435 if (action == null) throw new NullPointerException();
3436 Comparator<? super K> cmp = comparator;
3437 K f = fence;
3438 Node<K,V> e = current;
3439 current = null;
3440 for (; e != null; e = e.next) {
3441 K k; Object v;
3442 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3443 break;
3444 if ((v = e.value) != null && v != e) {
3445 @SuppressWarnings("unchecked") V vv = (V)v;
3446 action.accept(vv);
3447 }
3448 }
3449 }
3450
3451 public boolean tryAdvance(Consumer<? super V> action) {
3452 if (action == null) throw new NullPointerException();
3453 Comparator<? super K> cmp = comparator;
3454 K f = fence;
3455 Node<K,V> e = current;
3456 for (; e != null; e = e.next) {
3457 K k; Object v;
3458 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3459 e = null;
3460 break;
3461 }
3462 if ((v = e.value) != null && v != e) {
3463 current = e.next;
3464 @SuppressWarnings("unchecked") V vv = (V)v;
3465 action.accept(vv);
3466 return true;
3467 }
3468 }
3469 current = e;
3470 return false;
3471 }
3472
3473 public int characteristics() {
3474 return Spliterator.CONCURRENT | Spliterator.ORDERED |
3475 Spliterator.NONNULL;
3476 }
3477 }
3478
3479 // Almost the same as keySpliterator()
3480 final ValueSpliterator<K,V> valueSpliterator() {
3481 Comparator<? super K> cmp = comparator;
3482 for (;;) {
3483 HeadIndex<K,V> h; Node<K,V> p;
3484 Node<K,V> b = (h = head).node;
3485 if ((p = b.next) == null || p.value != null)
3486 return new ValueSpliterator<K,V>(cmp, h, p, null, (p == null) ?
3487 0 : Integer.MAX_VALUE);
3488 p.helpDelete(b, p.next);
3489 }
3490 }
3491
3492 static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
3493 implements Spliterator<Map.Entry<K,V>> {
3494 EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3495 Node<K,V> origin, K fence, int est) {
3496 super(comparator, row, origin, fence, est);
3497 }
3498
3499 public EntrySpliterator<K,V> trySplit() {
3500 Node<K,V> e; K ek;
3501 Comparator<? super K> cmp = comparator;
3502 K f = fence;
3503 if ((e = current) != null && (ek = e.key) != null) {
3504 for (Index<K,V> q = row; q != null; q = row = q.down) {
3505 Index<K,V> s; Node<K,V> b, n; K sk;
3506 if ((s = q.right) != null && (b = s.node) != null &&
3507 (n = b.next) != null && n.value != null &&
3508 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3509 (f == null || cpr(cmp, sk, f) < 0)) {
3510 current = n;
3511 Index<K,V> r = q.down;
3512 row = (s.right != null) ? s : s.down;
3513 est -= est >>> 2;
3514 return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
3515 }
3516 }
3517 }
3518 return null;
3519 }
3520
3521 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3522 if (action == null) throw new NullPointerException();
3523 Comparator<? super K> cmp = comparator;
3524 K f = fence;
3525 Node<K,V> e = current;
3526 current = null;
3527 for (; e != null; e = e.next) {
3528 K k; Object v;
3529 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3530 break;
3531 if ((v = e.value) != null && v != e) {
3532 @SuppressWarnings("unchecked") V vv = (V)v;
3533 action.accept
3534 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3535 }
3536 }
3537 }
3538
3539 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3540 if (action == null) throw new NullPointerException();
3541 Comparator<? super K> cmp = comparator;
3542 K f = fence;
3543 Node<K,V> e = current;
3544 for (; e != null; e = e.next) {
3545 K k; Object v;
3546 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3547 e = null;
3548 break;
3549 }
3550 if ((v = e.value) != null && v != e) {
3551 current = e.next;
3552 @SuppressWarnings("unchecked") V vv = (V)v;
3553 action.accept
3554 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3555 return true;
3556 }
3557 }
3558 current = e;
3559 return false;
3560 }
3561
3562 public int characteristics() {
3563 return Spliterator.DISTINCT | Spliterator.SORTED |
3564 Spliterator.ORDERED | Spliterator.CONCURRENT |
3565 Spliterator.NONNULL;
3566 }
3567
3568 public final Comparator<Map.Entry<K,V>> getComparator() {
3569 // Adapt or create a key-based comparator
3570 if (comparator != null) {
3571 return Map.Entry.comparingByKey(comparator);
3572 }
3573 else {
3574 return (Comparator<Map.Entry<K,V>> & Serializable) (e1, e2) -> {
3575 @SuppressWarnings("unchecked")
3576 Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3577 return k1.compareTo(e2.getKey());
3578 };
3579 }
3580 }
3581 }
3582
3583 // Almost the same as keySpliterator()
3584 final EntrySpliterator<K,V> entrySpliterator() {
3585 Comparator<? super K> cmp = comparator;
3586 for (;;) { // almost same as key version
3587 HeadIndex<K,V> h; Node<K,V> p;
3588 Node<K,V> b = (h = head).node;
3589 if ((p = b.next) == null || p.value != null)
3590 return new EntrySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3591 0 : Integer.MAX_VALUE);
3592 p.helpDelete(b, p.next);
3593 }
3594 }
3595
3596 // VarHandle mechanics
3597 private static final VarHandle HEAD;
3598 static {
3599 try {
3600 MethodHandles.Lookup l = MethodHandles.lookup();
3601 HEAD = l.findVarHandle(ConcurrentSkipListMap.class, "head",
3602 HeadIndex.class);
3603 } catch (ReflectiveOperationException e) {
3604 throw new Error(e);
3605 }
3606 }
3607 }