ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.164
Committed: Sat Sep 24 15:36:19 2016 UTC (7 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.163: +20 -3 lines
Log Message:
Avoid inconsistent reporting of isEmpty vs contains after clear()

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