ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.159
Committed: Wed Apr 27 19:19:34 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.158: +1 -1 lines
Log Message:
ConcurrentSkipListMap.SubMap should not implement Cloneable

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.io.Serializable;
10 import java.util.AbstractCollection;
11 import java.util.AbstractMap;
12 import java.util.AbstractSet;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.Comparator;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.NavigableMap;
21 import java.util.NavigableSet;
22 import java.util.NoSuchElementException;
23 import java.util.Set;
24 import java.util.SortedMap;
25 import java.util.Spliterator;
26 import java.util.function.BiConsumer;
27 import java.util.function.BiFunction;
28 import java.util.function.Consumer;
29 import java.util.function.Function;
30 import java.util.function.Predicate;
31
32 /**
33 * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
34 * The map is sorted according to the {@linkplain Comparable natural
35 * ordering} of its keys, or by a {@link Comparator} provided at map
36 * creation time, depending on which constructor is used.
37 *
38 * <p>This class implements a concurrent variant of <a
39 * href="http://en.wikipedia.org/wiki/Skip_list" target="_top">SkipLists</a>
40 * providing expected average <i>log(n)</i> time cost for the
41 * {@code containsKey}, {@code get}, {@code put} and
42 * {@code remove} operations and their variants. Insertion, removal,
43 * update, and access operations safely execute concurrently by
44 * multiple threads.
45 *
46 * <p>Iterators and spliterators are
47 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
48 *
49 * <p>Ascending key ordered views and their iterators are faster than
50 * descending ones.
51 *
52 * <p>All {@code Map.Entry} pairs returned by methods in this class
53 * and its views represent snapshots of mappings at the time they were
54 * produced. They do <em>not</em> support the {@code Entry.setValue}
55 * method. (Note however that it is possible to change mappings in the
56 * associated map using {@code put}, {@code putIfAbsent}, or
57 * {@code replace}, depending on exactly which effect you need.)
58 *
59 * <p>Beware that, unlike in most collections, the {@code size}
60 * method is <em>not</em> a constant-time operation. Because of the
61 * asynchronous nature of these maps, determining the current number
62 * of elements requires a traversal of the elements, and so may report
63 * inaccurate results if this collection is modified during traversal.
64 * Additionally, the bulk operations {@code putAll}, {@code equals},
65 * {@code toArray}, {@code containsValue}, and {@code clear} are
66 * <em>not</em> guaranteed to be performed atomically. For example, an
67 * iterator operating concurrently with a {@code putAll} operation
68 * might view only some of the added elements.
69 *
70 * <p>This class and its views and iterators implement all of the
71 * <em>optional</em> methods of the {@link Map} and {@link Iterator}
72 * interfaces. Like most other concurrent collections, this class does
73 * <em>not</em> permit the use of {@code null} keys or values because some
74 * null return values cannot be reliably distinguished from the absence of
75 * elements.
76 *
77 * <p>This class is a member of the
78 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
79 * Java Collections Framework</a>.
80 *
81 * @author Doug Lea
82 * @param <K> the type of keys maintained by this map
83 * @param <V> the type of mapped values
84 * @since 1.6
85 */
86 public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
87 implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable {
88 /*
89 * This class implements a tree-like two-dimensionally linked skip
90 * list in which the index levels are represented in separate
91 * nodes from the base nodes holding data. There are two reasons
92 * for taking this approach instead of the usual array-based
93 * structure: 1) Array based implementations seem to encounter
94 * more complexity and overhead 2) We can use cheaper algorithms
95 * for the heavily-traversed index lists than can be used for the
96 * base lists. Here's a picture of some of the basics for a
97 * possible list with 2 levels of index:
98 *
99 * Head nodes Index nodes
100 * +-+ right +-+ +-+
101 * |2|---------------->| |--------------------->| |->null
102 * +-+ +-+ +-+
103 * | down | |
104 * v v v
105 * +-+ +-+ +-+ +-+ +-+ +-+
106 * |1|----------->| |->| |------>| |----------->| |------>| |->null
107 * +-+ +-+ +-+ +-+ +-+ +-+
108 * v | | | | |
109 * Nodes next v v v v v
110 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
111 * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
112 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
113 *
114 * The base lists use a variant of the HM linked ordered set
115 * algorithm. See Tim Harris, "A pragmatic implementation of
116 * non-blocking linked lists"
117 * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
118 * Michael "High Performance Dynamic Lock-Free Hash Tables and
119 * List-Based Sets"
120 * http://www.research.ibm.com/people/m/michael/pubs.htm. The
121 * basic idea in these lists is to mark the "next" pointers of
122 * deleted nodes when deleting to avoid conflicts with concurrent
123 * insertions, and when traversing to keep track of triples
124 * (predecessor, node, successor) in order to detect when and how
125 * to unlink these deleted nodes.
126 *
127 * Rather than using mark-bits to mark list deletions (which can
128 * be slow and space-intensive using AtomicMarkedReference), nodes
129 * use direct CAS'able next pointers. On deletion, instead of
130 * marking a pointer, they splice in another node that can be
131 * thought of as standing for a marked pointer (indicating this by
132 * using otherwise impossible field values). Using plain nodes
133 * acts roughly like "boxed" implementations of marked pointers,
134 * but uses new nodes only when nodes are deleted, not for every
135 * link. This requires less space and supports faster
136 * traversal. Even if marked references were better supported by
137 * JVMs, traversal using this technique might still be faster
138 * because any search need only read ahead one more node than
139 * otherwise required (to check for trailing marker) rather than
140 * unmasking mark bits or whatever on each read.
141 *
142 * This approach maintains the essential property needed in the HM
143 * algorithm of changing the next-pointer of a deleted node so
144 * that any other CAS of it will fail, but implements the idea by
145 * changing the pointer to point to a different node, not by
146 * marking it. While it would be possible to further squeeze
147 * space by defining marker nodes not to have key/value fields, it
148 * isn't worth the extra type-testing overhead. The deletion
149 * markers are rarely encountered during traversal and are
150 * normally quickly garbage collected. (Note that this technique
151 * would not work well in systems without garbage collection.)
152 *
153 * In addition to using deletion markers, the lists also use
154 * nullness of value fields to indicate deletion, in a style
155 * similar to typical lazy-deletion schemes. If a node's value is
156 * null, then it is considered logically deleted and ignored even
157 * though it is still reachable. This maintains proper control of
158 * concurrent replace vs delete operations -- an attempted replace
159 * must fail if a delete beat it by nulling field, and a delete
160 * must return the last non-null value held in the field. (Note:
161 * Null, rather than some special marker, is used for value fields
162 * here because it just so happens to mesh with the Map API
163 * requirement that method get returns null if there is no
164 * mapping, which allows nodes to remain concurrently readable
165 * even when deleted. Using any other marker value here would be
166 * messy at best.)
167 *
168 * Here's the sequence of events for a deletion of node n with
169 * predecessor b and successor f, initially:
170 *
171 * +------+ +------+ +------+
172 * ... | b |------>| n |----->| f | ...
173 * +------+ +------+ +------+
174 *
175 * 1. CAS n's value field from non-null to null.
176 * From this point on, no public operations encountering
177 * the node consider this mapping to exist. However, other
178 * ongoing insertions and deletions might still modify
179 * n's next pointer.
180 *
181 * 2. CAS n's next pointer to point to a new marker node.
182 * From this point on, no other nodes can be appended to n.
183 * which avoids deletion errors in CAS-based linked lists.
184 *
185 * +------+ +------+ +------+ +------+
186 * ... | b |------>| n |----->|marker|------>| f | ...
187 * +------+ +------+ +------+ +------+
188 *
189 * 3. CAS b's next pointer over both n and its marker.
190 * From this point on, no new traversals will encounter n,
191 * and it can eventually be GCed.
192 * +------+ +------+
193 * ... | b |----------------------------------->| f | ...
194 * +------+ +------+
195 *
196 * A failure at step 1 leads to simple retry due to a lost race
197 * with another operation. Steps 2-3 can fail because some other
198 * thread noticed during a traversal a node with null value and
199 * helped out by marking and/or unlinking. This helping-out
200 * ensures that no thread can become stuck waiting for progress of
201 * the deleting thread. The use of marker nodes slightly
202 * complicates helping-out code because traversals must track
203 * consistent reads of up to four nodes (b, n, marker, f), not
204 * just (b, n, f), although the next field of a marker is
205 * immutable, and once a next field is CAS'ed to point to a
206 * marker, it never again changes, so this requires less care.
207 *
208 * Skip lists add indexing to this scheme, so that the base-level
209 * traversals start close to the locations being found, inserted
210 * or deleted -- usually base level traversals only traverse a few
211 * nodes. This doesn't change the basic algorithm except for the
212 * need to make sure base traversals start at predecessors (here,
213 * b) that are not (structurally) deleted, otherwise retrying
214 * after processing the deletion.
215 *
216 * Index levels are maintained as lists with volatile next fields,
217 * using CAS to link and unlink. Races are allowed in index-list
218 * operations that can (rarely) fail to link in a new index node
219 * or delete one. (We can't do this of course for data nodes.)
220 * However, even when this happens, the index lists remain sorted,
221 * so correctly serve as indices. This can impact performance,
222 * but since skip lists are probabilistic anyway, the net result
223 * is that under contention, the effective "p" value may be lower
224 * than its nominal value. And race windows are kept small enough
225 * that in practice these failures are rare, even under a lot of
226 * contention.
227 *
228 * The fact that retries (for both base and index lists) are
229 * relatively cheap due to indexing allows some minor
230 * simplifications of retry logic. Traversal restarts are
231 * performed after most "helping-out" CASes. This isn't always
232 * strictly necessary, but the implicit backoffs tend to help
233 * reduce other downstream failed CAS's enough to outweigh restart
234 * cost. This worsens the worst case, but seems to improve even
235 * highly contended cases.
236 *
237 * Unlike most skip-list implementations, index insertion and
238 * deletion here require a separate traversal pass occurring after
239 * the base-level action, to add or remove index nodes. This adds
240 * to single-threaded overhead, but improves contended
241 * multithreaded performance by narrowing interference windows,
242 * and allows deletion to ensure that all index nodes will be made
243 * unreachable upon return from a public remove operation, thus
244 * avoiding unwanted garbage retention. This is more important
245 * here than in some other data structures because we cannot null
246 * out node fields referencing user keys since they might still be
247 * read by other ongoing traversals.
248 *
249 * Indexing uses skip list parameters that maintain good search
250 * performance while using sparser-than-usual indices: The
251 * hardwired parameters k=1, p=0.5 (see method doPut) mean
252 * that about one-quarter of the nodes have indices. Of those that
253 * do, half have one level, a quarter have two, and so on (see
254 * Pugh's Skip List Cookbook, sec 3.4). The expected total space
255 * requirement for a map is slightly less than for the current
256 * implementation of java.util.TreeMap.
257 *
258 * Changing the level of the index (i.e, the height of the
259 * tree-like structure) also uses CAS. The head index has initial
260 * level/height of one. Creation of an index with height greater
261 * than the current level adds a level to the head index by
262 * CAS'ing on a new top-most head. To maintain good performance
263 * after a lot of removals, deletion methods heuristically try to
264 * reduce the height if the topmost levels appear to be empty.
265 * This may encounter races in which it possible (but rare) to
266 * reduce and "lose" a level just as it is about to contain an
267 * index (that will then never be encountered). This does no
268 * structural harm, and in practice appears to be a better option
269 * than allowing unrestrained growth of levels.
270 *
271 * The code for all this is more verbose than you'd like. Most
272 * operations entail locating an element (or position to insert an
273 * element). The code to do this can't be nicely factored out
274 * because subsequent uses require a snapshot of predecessor
275 * and/or successor and/or value fields which can't be returned
276 * all at once, at least not without creating yet another object
277 * to hold them -- creating such little objects is an especially
278 * bad idea for basic internal search operations because it adds
279 * to GC overhead. (This is one of the few times I've wished Java
280 * had macros.) Instead, some traversal code is interleaved within
281 * insertion and removal operations. The control logic to handle
282 * all the retry conditions is sometimes twisty. Most search is
283 * broken into 2 parts. findPredecessor() searches index nodes
284 * only, returning a base-level predecessor of the key. findNode()
285 * finishes out the base-level search. Even with this factoring,
286 * there is a fair amount of near-duplication of code to handle
287 * variants.
288 *
289 * To produce random values without interference across threads,
290 * we use within-JDK thread local random support (via the
291 * "secondary seed", to avoid interference with user-level
292 * ThreadLocalRandom.)
293 *
294 * A previous version of this class wrapped non-comparable keys
295 * with their comparators to emulate Comparables when using
296 * comparators vs Comparables. However, JVMs now appear to better
297 * handle infusing comparator-vs-comparable choice into search
298 * loops. Static method cpr(comparator, x, y) is used for all
299 * comparisons, which works well as long as the comparator
300 * argument is set up outside of loops (thus sometimes passed as
301 * an argument to internal methods) to avoid field re-reads.
302 *
303 * For explanation of algorithms sharing at least a couple of
304 * features with this one, see Mikhail Fomitchev's thesis
305 * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
306 * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
307 * thesis (http://www.cs.chalmers.se/~phs/).
308 *
309 * Given the use of tree-like index nodes, you might wonder why
310 * this doesn't use some kind of search tree instead, which would
311 * support somewhat faster search operations. The reason is that
312 * there are no known efficient lock-free insertion and deletion
313 * algorithms for search trees. The immutability of the "down"
314 * links of index nodes (as opposed to mutable "left" fields in
315 * true trees) makes this tractable using only CAS operations.
316 *
317 * Notation guide for local variables
318 * Node: b, n, f for predecessor, node, successor
319 * Index: q, r, d for index node, right, down.
320 * t for another index node
321 * Head: h
322 * Levels: j
323 * Keys: k, key
324 * Values: v, value
325 * Comparisons: c
326 */
327
328 private static final long serialVersionUID = -8627078645895051609L;
329
330 /**
331 * Special value used to identify base-level header.
332 */
333 static final Object BASE_HEADER = new Object();
334
335 /**
336 * The topmost head index of the skiplist.
337 */
338 private transient volatile HeadIndex<K,V> head;
339
340 /**
341 * The comparator used to maintain order in this map, or null if
342 * using natural ordering. (Non-private to simplify access in
343 * nested classes.)
344 * @serial
345 */
346 final Comparator<? super K> comparator;
347
348 /** Lazily initialized key set */
349 private transient KeySet<K,V> keySet;
350 /** Lazily initialized values collection */
351 private transient Values<K,V> values;
352 /** Lazily initialized entry set */
353 private transient EntrySet<K,V> entrySet;
354 /** Lazily initialized descending key set */
355 private transient SubMap<K,V> descendingMap;
356
357 /**
358 * Initializes or resets state. Needed by constructors, clone,
359 * clear, readObject. and ConcurrentSkipListSet.clone.
360 * (Note that comparator must be separately initialized.)
361 */
362 private void initialize() {
363 keySet = null;
364 entrySet = null;
365 values = null;
366 descendingMap = null;
367 head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),
368 null, null, 1);
369 }
370
371 /**
372 * compareAndSet head node.
373 */
374 private boolean casHead(HeadIndex<K,V> cmp, HeadIndex<K,V> val) {
375 return U.compareAndSwapObject(this, HEAD, cmp, val);
376 }
377
378 /* ---------------- Nodes -------------- */
379
380 /**
381 * Nodes hold keys and values, and are singly linked in sorted
382 * order, possibly with some intervening marker nodes. The list is
383 * headed by a dummy node accessible as head.node. The value field
384 * is declared only as Object because it takes special non-V
385 * values for marker and header nodes.
386 */
387 static final class Node<K,V> {
388 final K key;
389 volatile Object value;
390 volatile Node<K,V> next;
391
392 /**
393 * Creates a new regular node.
394 */
395 Node(K key, Object value, Node<K,V> next) {
396 this.key = key;
397 this.value = value;
398 this.next = next;
399 }
400
401 /**
402 * Creates a new marker node. A marker is distinguished by
403 * having its value field point to itself. Marker nodes also
404 * have null keys, a fact that is exploited in a few places,
405 * but this doesn't distinguish markers from the base-level
406 * header node (head.node), which also has a null key.
407 */
408 Node(Node<K,V> next) {
409 this.key = null;
410 this.value = this;
411 this.next = next;
412 }
413
414 /**
415 * compareAndSet value field.
416 */
417 boolean casValue(Object cmp, Object val) {
418 return U.compareAndSwapObject(this, VALUE, cmp, val);
419 }
420
421 /**
422 * compareAndSet next field.
423 */
424 boolean casNext(Node<K,V> cmp, Node<K,V> val) {
425 return U.compareAndSwapObject(this, NEXT, cmp, val);
426 }
427
428 /**
429 * Returns true if this node is a marker. This method isn't
430 * actually called in any current code checking for markers
431 * because callers will have already read value field and need
432 * to use that read (not another done here) and so directly
433 * test if value points to node.
434 *
435 * @return true if this node is a marker node
436 */
437 boolean isMarker() {
438 return value == this;
439 }
440
441 /**
442 * Returns true if this node is the header of base-level list.
443 * @return true if this node is header node
444 */
445 boolean isBaseHeader() {
446 return value == BASE_HEADER;
447 }
448
449 /**
450 * Tries to append a deletion marker to this node.
451 * @param f the assumed current successor of this node
452 * @return true if successful
453 */
454 boolean appendMarker(Node<K,V> f) {
455 return casNext(f, new Node<K,V>(f));
456 }
457
458 /**
459 * Helps out a deletion by appending marker or unlinking from
460 * predecessor. This is called during traversals when value
461 * field seen to be null.
462 * @param b predecessor
463 * @param f successor
464 */
465 void helpDelete(Node<K,V> b, Node<K,V> f) {
466 /*
467 * Rechecking links and then doing only one of the
468 * help-out stages per call tends to minimize CAS
469 * interference among helping threads.
470 */
471 if (f == next && this == b.next) {
472 if (f == null || f.value != f) // not already marked
473 casNext(f, new Node<K,V>(f));
474 else
475 b.casNext(this, f.next);
476 }
477 }
478
479 /**
480 * Returns value if this node contains a valid key-value pair,
481 * else null.
482 * @return this node's value if it isn't a marker or header or
483 * is deleted, else null
484 */
485 V getValidValue() {
486 Object v = value;
487 if (v == this || v == BASE_HEADER)
488 return null;
489 @SuppressWarnings("unchecked") V vv = (V)v;
490 return vv;
491 }
492
493 /**
494 * Creates and returns a new SimpleImmutableEntry holding current
495 * mapping if this node holds a valid value, else null.
496 * @return new entry or null
497 */
498 AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
499 Object v = value;
500 if (v == null || v == this || v == BASE_HEADER)
501 return null;
502 @SuppressWarnings("unchecked") V vv = (V)v;
503 return new AbstractMap.SimpleImmutableEntry<K,V>(key, vv);
504 }
505
506 // Unsafe mechanics
507
508 private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
509 private static final long VALUE;
510 private static final long NEXT;
511
512 static {
513 try {
514 VALUE = U.objectFieldOffset
515 (Node.class.getDeclaredField("value"));
516 NEXT = U.objectFieldOffset
517 (Node.class.getDeclaredField("next"));
518 } catch (ReflectiveOperationException e) {
519 throw new Error(e);
520 }
521 }
522 }
523
524 /* ---------------- Indexing -------------- */
525
526 /**
527 * Index nodes represent the levels of the skip list. Note that
528 * even though both Nodes and Indexes have forward-pointing
529 * fields, they have different types and are handled in different
530 * ways, that can't nicely be captured by placing field in a
531 * shared abstract class.
532 */
533 static class Index<K,V> {
534 final Node<K,V> node;
535 final Index<K,V> down;
536 volatile Index<K,V> right;
537
538 /**
539 * Creates index node with given values.
540 */
541 Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
542 this.node = node;
543 this.down = down;
544 this.right = right;
545 }
546
547 /**
548 * compareAndSet right field.
549 */
550 final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
551 return U.compareAndSwapObject(this, RIGHT, cmp, val);
552 }
553
554 /**
555 * Returns true if the node this indexes has been deleted.
556 * @return true if indexed node is known to be deleted
557 */
558 final boolean indexesDeletedNode() {
559 return node.value == null;
560 }
561
562 /**
563 * Tries to CAS newSucc as successor. To minimize races with
564 * unlink that may lose this index node, if the node being
565 * indexed is known to be deleted, it doesn't try to link in.
566 * @param succ the expected current successor
567 * @param newSucc the new successor
568 * @return true if successful
569 */
570 final boolean link(Index<K,V> succ, Index<K,V> newSucc) {
571 Node<K,V> n = node;
572 newSucc.right = succ;
573 return n.value != null && casRight(succ, newSucc);
574 }
575
576 /**
577 * Tries to CAS right field to skip over apparent successor
578 * succ. Fails (forcing a retraversal by caller) if this node
579 * is known to be deleted.
580 * @param succ the expected current successor
581 * @return true if successful
582 */
583 final boolean unlink(Index<K,V> succ) {
584 return node.value != null && casRight(succ, succ.right);
585 }
586
587 // Unsafe mechanics
588 private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
589 private static final long RIGHT;
590 static {
591 try {
592 RIGHT = U.objectFieldOffset
593 (Index.class.getDeclaredField("right"));
594 } catch (ReflectiveOperationException e) {
595 throw new Error(e);
596 }
597 }
598 }
599
600 /* ---------------- Head nodes -------------- */
601
602 /**
603 * Nodes heading each level keep track of their level.
604 */
605 static final class HeadIndex<K,V> extends Index<K,V> {
606 final int level;
607 HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) {
608 super(node, down, right);
609 this.level = level;
610 }
611 }
612
613 /* ---------------- Comparison utilities -------------- */
614
615 /**
616 * Compares using comparator or natural ordering if null.
617 * Called only by methods that have performed required type checks.
618 */
619 @SuppressWarnings({"unchecked", "rawtypes"})
620 static final int cpr(Comparator c, Object x, Object y) {
621 return (c != null) ? c.compare(x, y) : ((Comparable)x).compareTo(y);
622 }
623
624 /* ---------------- Traversal -------------- */
625
626 /**
627 * Returns a base-level node with key strictly less than given key,
628 * or the base-level header if there is no such node. Also
629 * unlinks indexes to deleted nodes found along the way. Callers
630 * rely on this side-effect of clearing indices to deleted nodes.
631 * @param key the key
632 * @return a predecessor of key
633 */
634 private Node<K,V> findPredecessor(Object key, Comparator<? super K> cmp) {
635 if (key == null)
636 throw new NullPointerException(); // don't postpone errors
637 for (;;) {
638 for (Index<K,V> q = head, r = q.right, d;;) {
639 if (r != null) {
640 Node<K,V> n = r.node;
641 K k = n.key;
642 if (n.value == null) {
643 if (!q.unlink(r))
644 break; // restart
645 r = q.right; // reread r
646 continue;
647 }
648 if (cpr(cmp, key, k) > 0) {
649 q = r;
650 r = r.right;
651 continue;
652 }
653 }
654 if ((d = q.down) == null)
655 return q.node;
656 q = d;
657 r = d.right;
658 }
659 }
660 }
661
662 /**
663 * Returns node holding key or null if no such, clearing out any
664 * deleted nodes seen along the way. Repeatedly traverses at
665 * base-level looking for key starting at predecessor returned
666 * from findPredecessor, processing base-level deletions as
667 * encountered. Some callers rely on this side-effect of clearing
668 * deleted nodes.
669 *
670 * Restarts occur, at traversal step centered on node n, if:
671 *
672 * (1) After reading n's next field, n is no longer assumed
673 * predecessor b's current successor, which means that
674 * we don't have a consistent 3-node snapshot and so cannot
675 * unlink any subsequent deleted nodes encountered.
676 *
677 * (2) n's value field is null, indicating n is deleted, in
678 * which case we help out an ongoing structural deletion
679 * before retrying. Even though there are cases where such
680 * unlinking doesn't require restart, they aren't sorted out
681 * here because doing so would not usually outweigh cost of
682 * restarting.
683 *
684 * (3) n is a marker or n's predecessor's value field is null,
685 * indicating (among other possibilities) that
686 * findPredecessor returned a deleted node. We can't unlink
687 * the node because we don't know its predecessor, so rely
688 * on another call to findPredecessor to notice and return
689 * some earlier predecessor, which it will do. This check is
690 * only strictly needed at beginning of loop, (and the
691 * b.value check isn't strictly needed at all) but is done
692 * each iteration to help avoid contention with other
693 * threads by callers that will fail to be able to change
694 * links, and so will retry anyway.
695 *
696 * The traversal loops in doPut, doRemove, and findNear all
697 * include the same three kinds of checks. And specialized
698 * versions appear in findFirst, and findLast and their variants.
699 * They can't easily share code because each uses the reads of
700 * fields held in locals occurring in the orders they were
701 * performed.
702 *
703 * @param key the key
704 * @return node holding key, or null if no such
705 */
706 private Node<K,V> findNode(Object key) {
707 if (key == null)
708 throw new NullPointerException(); // don't postpone errors
709 Comparator<? super K> cmp = comparator;
710 outer: for (;;) {
711 for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
712 Object v; int c;
713 if (n == null)
714 break outer;
715 Node<K,V> f = n.next;
716 if (n != b.next) // inconsistent read
717 break;
718 if ((v = n.value) == null) { // n is deleted
719 n.helpDelete(b, f);
720 break;
721 }
722 if (b.value == null || v == n) // b is deleted
723 break;
724 if ((c = cpr(cmp, key, n.key)) == 0)
725 return n;
726 if (c < 0)
727 break outer;
728 b = n;
729 n = f;
730 }
731 }
732 return null;
733 }
734
735 /**
736 * Gets value for key. Almost the same as findNode, but returns
737 * the found value (to avoid retries during re-reads)
738 *
739 * @param key the key
740 * @return the value, or null if absent
741 */
742 private V doGet(Object key) {
743 if (key == null)
744 throw new NullPointerException();
745 Comparator<? super K> cmp = comparator;
746 outer: for (;;) {
747 for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
748 Object v; int c;
749 if (n == null)
750 break outer;
751 Node<K,V> f = n.next;
752 if (n != b.next) // inconsistent read
753 break;
754 if ((v = n.value) == null) { // n is deleted
755 n.helpDelete(b, f);
756 break;
757 }
758 if (b.value == null || v == n) // b is deleted
759 break;
760 if ((c = cpr(cmp, key, n.key)) == 0) {
761 @SuppressWarnings("unchecked") V vv = (V)v;
762 return vv;
763 }
764 if (c < 0)
765 break outer;
766 b = n;
767 n = f;
768 }
769 }
770 return null;
771 }
772
773 /* ---------------- Insertion -------------- */
774
775 /**
776 * Main insertion method. Adds element if not present, or
777 * replaces value if present and onlyIfAbsent is false.
778 * @param key the key
779 * @param value the value that must be associated with key
780 * @param onlyIfAbsent if should not insert if already present
781 * @return the old value, or null if newly inserted
782 */
783 private V doPut(K key, V value, boolean onlyIfAbsent) {
784 Node<K,V> z; // added node
785 if (key == null)
786 throw new NullPointerException();
787 Comparator<? super K> cmp = comparator;
788 outer: for (;;) {
789 for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
790 if (n != null) {
791 Object v; int c;
792 Node<K,V> f = n.next;
793 if (n != b.next) // inconsistent read
794 break;
795 if ((v = n.value) == null) { // n is deleted
796 n.helpDelete(b, f);
797 break;
798 }
799 if (b.value == null || v == n) // b is deleted
800 break;
801 if ((c = cpr(cmp, key, n.key)) > 0) {
802 b = n;
803 n = f;
804 continue;
805 }
806 if (c == 0) {
807 if (onlyIfAbsent || n.casValue(v, value)) {
808 @SuppressWarnings("unchecked") V vv = (V)v;
809 return vv;
810 }
811 break; // restart if lost race to replace value
812 }
813 // else c < 0; fall through
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 initialize();
1625 }
1626
1627 /**
1628 * If the specified key is not already associated with a value,
1629 * attempts to compute its value using the given mapping function
1630 * and enters it into this map unless {@code null}. The function
1631 * is <em>NOT</em> guaranteed to be applied once atomically only
1632 * if the value is not present.
1633 *
1634 * @param key key with which the specified value is to be associated
1635 * @param mappingFunction the function to compute a value
1636 * @return the current (existing or computed) value associated with
1637 * the specified key, or null if the computed value is null
1638 * @throws NullPointerException if the specified key is null
1639 * or the mappingFunction is null
1640 * @since 1.8
1641 */
1642 public V computeIfAbsent(K key,
1643 Function<? super K, ? extends V> mappingFunction) {
1644 if (key == null || mappingFunction == null)
1645 throw new NullPointerException();
1646 V v, p, r;
1647 if ((v = doGet(key)) == null &&
1648 (r = mappingFunction.apply(key)) != null)
1649 v = (p = doPut(key, r, true)) == null ? r : p;
1650 return v;
1651 }
1652
1653 /**
1654 * If the value for the specified key is present, attempts to
1655 * compute a new mapping given the key and its current mapped
1656 * value. The function is <em>NOT</em> guaranteed to be applied
1657 * once atomically.
1658 *
1659 * @param key key with which a value may be associated
1660 * @param remappingFunction the function to compute a value
1661 * @return the new value associated with the specified key, or null if none
1662 * @throws NullPointerException if the specified key is null
1663 * or the remappingFunction is null
1664 * @since 1.8
1665 */
1666 public V computeIfPresent(K key,
1667 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1668 if (key == null || remappingFunction == null)
1669 throw new NullPointerException();
1670 Node<K,V> n; Object v;
1671 while ((n = findNode(key)) != null) {
1672 if ((v = n.value) != null) {
1673 @SuppressWarnings("unchecked") V vv = (V) v;
1674 V r = remappingFunction.apply(key, vv);
1675 if (r != null) {
1676 if (n.casValue(vv, r))
1677 return r;
1678 }
1679 else if (doRemove(key, vv) != null)
1680 break;
1681 }
1682 }
1683 return null;
1684 }
1685
1686 /**
1687 * Attempts to compute a mapping for the specified key and its
1688 * current mapped value (or {@code null} if there is no current
1689 * mapping). The function is <em>NOT</em> guaranteed to be applied
1690 * once atomically.
1691 *
1692 * @param key key with which the specified value is to be associated
1693 * @param remappingFunction the function to compute a value
1694 * @return the new value associated with the specified key, or null if none
1695 * @throws NullPointerException if the specified key is null
1696 * or the remappingFunction is null
1697 * @since 1.8
1698 */
1699 public V compute(K key,
1700 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1701 if (key == null || remappingFunction == null)
1702 throw new NullPointerException();
1703 for (;;) {
1704 Node<K,V> n; Object v; V r;
1705 if ((n = findNode(key)) == null) {
1706 if ((r = remappingFunction.apply(key, null)) == null)
1707 break;
1708 if (doPut(key, r, true) == null)
1709 return r;
1710 }
1711 else if ((v = n.value) != null) {
1712 @SuppressWarnings("unchecked") V vv = (V) v;
1713 if ((r = remappingFunction.apply(key, vv)) != null) {
1714 if (n.casValue(vv, r))
1715 return r;
1716 }
1717 else if (doRemove(key, vv) != null)
1718 break;
1719 }
1720 }
1721 return null;
1722 }
1723
1724 /**
1725 * If the specified key is not already associated with a value,
1726 * associates it with the given value. Otherwise, replaces the
1727 * value with the results of the given remapping function, or
1728 * removes if {@code null}. The function is <em>NOT</em>
1729 * guaranteed to be applied once atomically.
1730 *
1731 * @param key key with which the specified value is to be associated
1732 * @param value the value to use if absent
1733 * @param remappingFunction the function to recompute a value if present
1734 * @return the new value associated with the specified key, or null if none
1735 * @throws NullPointerException if the specified key or value is null
1736 * or the remappingFunction is null
1737 * @since 1.8
1738 */
1739 public V merge(K key, V value,
1740 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1741 if (key == null || value == null || remappingFunction == null)
1742 throw new NullPointerException();
1743 for (;;) {
1744 Node<K,V> n; Object v; V r;
1745 if ((n = findNode(key)) == null) {
1746 if (doPut(key, value, true) == null)
1747 return value;
1748 }
1749 else if ((v = n.value) != null) {
1750 @SuppressWarnings("unchecked") V vv = (V) v;
1751 if ((r = remappingFunction.apply(vv, value)) != null) {
1752 if (n.casValue(vv, r))
1753 return r;
1754 }
1755 else if (doRemove(key, vv) != null)
1756 return null;
1757 }
1758 }
1759 }
1760
1761 /* ---------------- View methods -------------- */
1762
1763 /*
1764 * Note: Lazy initialization works for views because view classes
1765 * are stateless/immutable so it doesn't matter wrt correctness if
1766 * more than one is created (which will only rarely happen). Even
1767 * so, the following idiom conservatively ensures that the method
1768 * returns the one it created if it does so, not one created by
1769 * another racing thread.
1770 */
1771
1772 /**
1773 * Returns a {@link NavigableSet} view of the keys contained in this map.
1774 *
1775 * <p>The set's iterator returns the keys in ascending order.
1776 * The set's spliterator additionally reports {@link Spliterator#CONCURRENT},
1777 * {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
1778 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1779 * key order. The spliterator's comparator (see
1780 * {@link java.util.Spliterator#getComparator()}) is {@code null} if
1781 * the map's comparator (see {@link #comparator()}) is {@code null}.
1782 * Otherwise, the spliterator's comparator is the same as or imposes the
1783 * same total ordering as the map's comparator.
1784 *
1785 * <p>The set is backed by the map, so changes to the map are
1786 * reflected in the set, and vice-versa. The set supports element
1787 * removal, which removes the corresponding mapping from the map,
1788 * via the {@code Iterator.remove}, {@code Set.remove},
1789 * {@code removeAll}, {@code retainAll}, and {@code clear}
1790 * operations. It does not support the {@code add} or {@code addAll}
1791 * operations.
1792 *
1793 * <p>The view's iterators and spliterators are
1794 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1795 *
1796 * <p>This method is equivalent to method {@code navigableKeySet}.
1797 *
1798 * @return a navigable set view of the keys in this map
1799 */
1800 public NavigableSet<K> keySet() {
1801 KeySet<K,V> ks;
1802 if ((ks = keySet) != null) return ks;
1803 return keySet = new KeySet<>(this);
1804 }
1805
1806 public NavigableSet<K> navigableKeySet() {
1807 KeySet<K,V> ks;
1808 if ((ks = keySet) != null) return ks;
1809 return keySet = new KeySet<>(this);
1810 }
1811
1812 /**
1813 * Returns a {@link Collection} view of the values contained in this map.
1814 * <p>The collection's iterator returns the values in ascending order
1815 * of the corresponding keys. The collections's spliterator additionally
1816 * reports {@link Spliterator#CONCURRENT}, {@link Spliterator#NONNULL} and
1817 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1818 * order of the corresponding keys.
1819 *
1820 * <p>The collection is backed by the map, so changes to the map are
1821 * reflected in the collection, and vice-versa. The collection
1822 * supports element removal, which removes the corresponding
1823 * mapping from the map, via the {@code Iterator.remove},
1824 * {@code Collection.remove}, {@code removeAll},
1825 * {@code retainAll} and {@code clear} operations. It does not
1826 * support the {@code add} or {@code addAll} operations.
1827 *
1828 * <p>The view's iterators and spliterators are
1829 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1830 */
1831 public Collection<V> values() {
1832 Values<K,V> vs;
1833 if ((vs = values) != null) return vs;
1834 return values = new Values<>(this);
1835 }
1836
1837 /**
1838 * Returns a {@link Set} view of the mappings contained in this map.
1839 *
1840 * <p>The set's iterator returns the entries in ascending key order. The
1841 * set's spliterator additionally reports {@link Spliterator#CONCURRENT},
1842 * {@link Spliterator#NONNULL}, {@link Spliterator#SORTED} and
1843 * {@link Spliterator#ORDERED}, with an encounter order that is ascending
1844 * key order.
1845 *
1846 * <p>The set is backed by the map, so changes to the map are
1847 * reflected in the set, and vice-versa. The set supports element
1848 * removal, which removes the corresponding mapping from the map,
1849 * via the {@code Iterator.remove}, {@code Set.remove},
1850 * {@code removeAll}, {@code retainAll} and {@code clear}
1851 * operations. It does not support the {@code add} or
1852 * {@code addAll} operations.
1853 *
1854 * <p>The view's iterators and spliterators are
1855 * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
1856 *
1857 * <p>The {@code Map.Entry} elements traversed by the {@code iterator}
1858 * or {@code spliterator} do <em>not</em> support the {@code setValue}
1859 * operation.
1860 *
1861 * @return a set view of the mappings contained in this map,
1862 * sorted in ascending key order
1863 */
1864 public Set<Map.Entry<K,V>> entrySet() {
1865 EntrySet<K,V> es;
1866 if ((es = entrySet) != null) return es;
1867 return entrySet = new EntrySet<K,V>(this);
1868 }
1869
1870 public ConcurrentNavigableMap<K,V> descendingMap() {
1871 ConcurrentNavigableMap<K,V> dm;
1872 if ((dm = descendingMap) != null) return dm;
1873 return descendingMap =
1874 new SubMap<K,V>(this, null, false, null, false, true);
1875 }
1876
1877 public NavigableSet<K> descendingKeySet() {
1878 return descendingMap().navigableKeySet();
1879 }
1880
1881 /* ---------------- AbstractMap Overrides -------------- */
1882
1883 /**
1884 * Compares the specified object with this map for equality.
1885 * Returns {@code true} if the given object is also a map and the
1886 * two maps represent the same mappings. More formally, two maps
1887 * {@code m1} and {@code m2} represent the same mappings if
1888 * {@code m1.entrySet().equals(m2.entrySet())}. This
1889 * operation may return misleading results if either map is
1890 * concurrently modified during execution of this method.
1891 *
1892 * @param o object to be compared for equality with this map
1893 * @return {@code true} if the specified object is equal to this map
1894 */
1895 public boolean equals(Object o) {
1896 if (o == this)
1897 return true;
1898 if (!(o instanceof Map))
1899 return false;
1900 Map<?,?> m = (Map<?,?>) o;
1901 try {
1902 for (Map.Entry<K,V> e : this.entrySet())
1903 if (! e.getValue().equals(m.get(e.getKey())))
1904 return false;
1905 for (Map.Entry<?,?> e : m.entrySet()) {
1906 Object k = e.getKey();
1907 Object v = e.getValue();
1908 if (k == null || v == null || !v.equals(get(k)))
1909 return false;
1910 }
1911 return true;
1912 } catch (ClassCastException unused) {
1913 return false;
1914 } catch (NullPointerException unused) {
1915 return false;
1916 }
1917 }
1918
1919 /* ------ ConcurrentMap API methods ------ */
1920
1921 /**
1922 * {@inheritDoc}
1923 *
1924 * @return the previous value associated with the specified key,
1925 * or {@code null} if there was no mapping for the key
1926 * @throws ClassCastException if the specified key cannot be compared
1927 * with the keys currently in the map
1928 * @throws NullPointerException if the specified key or value is null
1929 */
1930 public V putIfAbsent(K key, V value) {
1931 if (value == null)
1932 throw new NullPointerException();
1933 return doPut(key, value, true);
1934 }
1935
1936 /**
1937 * {@inheritDoc}
1938 *
1939 * @throws ClassCastException if the specified key cannot be compared
1940 * with the keys currently in the map
1941 * @throws NullPointerException if the specified key is null
1942 */
1943 public boolean remove(Object key, Object value) {
1944 if (key == null)
1945 throw new NullPointerException();
1946 return value != null && doRemove(key, value) != null;
1947 }
1948
1949 /**
1950 * {@inheritDoc}
1951 *
1952 * @throws ClassCastException if the specified key cannot be compared
1953 * with the keys currently in the map
1954 * @throws NullPointerException if any of the arguments are null
1955 */
1956 public boolean replace(K key, V oldValue, V newValue) {
1957 if (key == null || oldValue == null || newValue == null)
1958 throw new NullPointerException();
1959 for (;;) {
1960 Node<K,V> n; Object v;
1961 if ((n = findNode(key)) == null)
1962 return false;
1963 if ((v = n.value) != null) {
1964 if (!oldValue.equals(v))
1965 return false;
1966 if (n.casValue(v, newValue))
1967 return true;
1968 }
1969 }
1970 }
1971
1972 /**
1973 * {@inheritDoc}
1974 *
1975 * @return the previous value associated with the specified key,
1976 * or {@code null} if there was no mapping for the key
1977 * @throws ClassCastException if the specified key cannot be compared
1978 * with the keys currently in the map
1979 * @throws NullPointerException if the specified key or value is null
1980 */
1981 public V replace(K key, V value) {
1982 if (key == null || value == null)
1983 throw new NullPointerException();
1984 for (;;) {
1985 Node<K,V> n; Object v;
1986 if ((n = findNode(key)) == null)
1987 return null;
1988 if ((v = n.value) != null && n.casValue(v, value)) {
1989 @SuppressWarnings("unchecked") V vv = (V)v;
1990 return vv;
1991 }
1992 }
1993 }
1994
1995 /* ------ SortedMap API methods ------ */
1996
1997 public Comparator<? super K> comparator() {
1998 return comparator;
1999 }
2000
2001 /**
2002 * @throws NoSuchElementException {@inheritDoc}
2003 */
2004 public K firstKey() {
2005 Node<K,V> n = findFirst();
2006 if (n == null)
2007 throw new NoSuchElementException();
2008 return n.key;
2009 }
2010
2011 /**
2012 * @throws NoSuchElementException {@inheritDoc}
2013 */
2014 public K lastKey() {
2015 Node<K,V> n = findLast();
2016 if (n == null)
2017 throw new NoSuchElementException();
2018 return n.key;
2019 }
2020
2021 /**
2022 * @throws ClassCastException {@inheritDoc}
2023 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2024 * @throws IllegalArgumentException {@inheritDoc}
2025 */
2026 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
2027 boolean fromInclusive,
2028 K toKey,
2029 boolean toInclusive) {
2030 if (fromKey == null || toKey == null)
2031 throw new NullPointerException();
2032 return new SubMap<K,V>
2033 (this, fromKey, fromInclusive, toKey, toInclusive, false);
2034 }
2035
2036 /**
2037 * @throws ClassCastException {@inheritDoc}
2038 * @throws NullPointerException if {@code toKey} is null
2039 * @throws IllegalArgumentException {@inheritDoc}
2040 */
2041 public ConcurrentNavigableMap<K,V> headMap(K toKey,
2042 boolean inclusive) {
2043 if (toKey == null)
2044 throw new NullPointerException();
2045 return new SubMap<K,V>
2046 (this, null, false, toKey, inclusive, false);
2047 }
2048
2049 /**
2050 * @throws ClassCastException {@inheritDoc}
2051 * @throws NullPointerException if {@code fromKey} is null
2052 * @throws IllegalArgumentException {@inheritDoc}
2053 */
2054 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2055 boolean inclusive) {
2056 if (fromKey == null)
2057 throw new NullPointerException();
2058 return new SubMap<K,V>
2059 (this, fromKey, inclusive, null, false, false);
2060 }
2061
2062 /**
2063 * @throws ClassCastException {@inheritDoc}
2064 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2065 * @throws IllegalArgumentException {@inheritDoc}
2066 */
2067 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2068 return subMap(fromKey, true, toKey, false);
2069 }
2070
2071 /**
2072 * @throws ClassCastException {@inheritDoc}
2073 * @throws NullPointerException if {@code toKey} is null
2074 * @throws IllegalArgumentException {@inheritDoc}
2075 */
2076 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2077 return headMap(toKey, false);
2078 }
2079
2080 /**
2081 * @throws ClassCastException {@inheritDoc}
2082 * @throws NullPointerException if {@code fromKey} is null
2083 * @throws IllegalArgumentException {@inheritDoc}
2084 */
2085 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2086 return tailMap(fromKey, true);
2087 }
2088
2089 /* ---------------- Relational operations -------------- */
2090
2091 /**
2092 * Returns a key-value mapping associated with the greatest key
2093 * strictly less than the given key, or {@code null} if there is
2094 * no such key. The returned entry does <em>not</em> support the
2095 * {@code Entry.setValue} method.
2096 *
2097 * @throws ClassCastException {@inheritDoc}
2098 * @throws NullPointerException if the specified key is null
2099 */
2100 public Map.Entry<K,V> lowerEntry(K key) {
2101 return getNear(key, LT);
2102 }
2103
2104 /**
2105 * @throws ClassCastException {@inheritDoc}
2106 * @throws NullPointerException if the specified key is null
2107 */
2108 public K lowerKey(K key) {
2109 Node<K,V> n = findNear(key, LT, comparator);
2110 return (n == null) ? null : n.key;
2111 }
2112
2113 /**
2114 * Returns a key-value mapping associated with the greatest key
2115 * less than or equal to the given key, or {@code null} if there
2116 * is no such key. The returned entry does <em>not</em> support
2117 * the {@code Entry.setValue} method.
2118 *
2119 * @param key the key
2120 * @throws ClassCastException {@inheritDoc}
2121 * @throws NullPointerException if the specified key is null
2122 */
2123 public Map.Entry<K,V> floorEntry(K key) {
2124 return getNear(key, LT|EQ);
2125 }
2126
2127 /**
2128 * @param key the key
2129 * @throws ClassCastException {@inheritDoc}
2130 * @throws NullPointerException if the specified key is null
2131 */
2132 public K floorKey(K key) {
2133 Node<K,V> n = findNear(key, LT|EQ, comparator);
2134 return (n == null) ? null : n.key;
2135 }
2136
2137 /**
2138 * Returns a key-value mapping associated with the least key
2139 * greater than or equal to the given key, or {@code null} if
2140 * there is no such entry. The returned entry does <em>not</em>
2141 * support the {@code Entry.setValue} method.
2142 *
2143 * @throws ClassCastException {@inheritDoc}
2144 * @throws NullPointerException if the specified key is null
2145 */
2146 public Map.Entry<K,V> ceilingEntry(K key) {
2147 return getNear(key, GT|EQ);
2148 }
2149
2150 /**
2151 * @throws ClassCastException {@inheritDoc}
2152 * @throws NullPointerException if the specified key is null
2153 */
2154 public K ceilingKey(K key) {
2155 Node<K,V> n = findNear(key, GT|EQ, comparator);
2156 return (n == null) ? null : n.key;
2157 }
2158
2159 /**
2160 * Returns a key-value mapping associated with the least key
2161 * strictly greater than the given key, or {@code null} if there
2162 * is no such key. The returned entry does <em>not</em> support
2163 * the {@code Entry.setValue} method.
2164 *
2165 * @param key the key
2166 * @throws ClassCastException {@inheritDoc}
2167 * @throws NullPointerException if the specified key is null
2168 */
2169 public Map.Entry<K,V> higherEntry(K key) {
2170 return getNear(key, GT);
2171 }
2172
2173 /**
2174 * @param key the key
2175 * @throws ClassCastException {@inheritDoc}
2176 * @throws NullPointerException if the specified key is null
2177 */
2178 public K higherKey(K key) {
2179 Node<K,V> n = findNear(key, GT, comparator);
2180 return (n == null) ? null : n.key;
2181 }
2182
2183 /**
2184 * Returns a key-value mapping associated with the least
2185 * key in this map, or {@code null} if the map is empty.
2186 * The returned entry does <em>not</em> support
2187 * the {@code Entry.setValue} method.
2188 */
2189 public Map.Entry<K,V> firstEntry() {
2190 for (;;) {
2191 Node<K,V> n = findFirst();
2192 if (n == null)
2193 return null;
2194 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2195 if (e != null)
2196 return e;
2197 }
2198 }
2199
2200 /**
2201 * Returns a key-value mapping associated with the greatest
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> lastEntry() {
2207 for (;;) {
2208 Node<K,V> n = findLast();
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 * Removes and returns a key-value mapping associated with
2219 * the least 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> pollFirstEntry() {
2224 return doRemoveFirstEntry();
2225 }
2226
2227 /**
2228 * Removes and returns a key-value mapping associated with
2229 * the greatest key in this map, or {@code null} if the map is empty.
2230 * The returned entry does <em>not</em> support
2231 * the {@code Entry.setValue} method.
2232 */
2233 public Map.Entry<K,V> pollLastEntry() {
2234 return doRemoveLastEntry();
2235 }
2236
2237
2238 /* ---------------- Iterators -------------- */
2239
2240 /**
2241 * Base of iterator classes:
2242 */
2243 abstract class Iter<T> implements Iterator<T> {
2244 /** the last node returned by next() */
2245 Node<K,V> lastReturned;
2246 /** the next node to return from next(); */
2247 Node<K,V> next;
2248 /** Cache of next value field to maintain weak consistency */
2249 V nextValue;
2250
2251 /** Initializes ascending iterator for entire range. */
2252 Iter() {
2253 while ((next = findFirst()) != null) {
2254 Object x = next.value;
2255 if (x != null && x != next) {
2256 @SuppressWarnings("unchecked") V vv = (V)x;
2257 nextValue = vv;
2258 break;
2259 }
2260 }
2261 }
2262
2263 public final boolean hasNext() {
2264 return next != null;
2265 }
2266
2267 /** Advances next to higher entry. */
2268 final void advance() {
2269 if (next == null)
2270 throw new NoSuchElementException();
2271 lastReturned = next;
2272 while ((next = next.next) != null) {
2273 Object x = next.value;
2274 if (x != null && x != next) {
2275 @SuppressWarnings("unchecked") V vv = (V)x;
2276 nextValue = vv;
2277 break;
2278 }
2279 }
2280 }
2281
2282 public void remove() {
2283 Node<K,V> l = lastReturned;
2284 if (l == null)
2285 throw new IllegalStateException();
2286 // It would not be worth all of the overhead to directly
2287 // unlink from here. Using remove is fast enough.
2288 ConcurrentSkipListMap.this.remove(l.key);
2289 lastReturned = null;
2290 }
2291
2292 }
2293
2294 final class ValueIterator extends Iter<V> {
2295 public V next() {
2296 V v = nextValue;
2297 advance();
2298 return v;
2299 }
2300 }
2301
2302 final class KeyIterator extends Iter<K> {
2303 public K next() {
2304 Node<K,V> n = next;
2305 advance();
2306 return n.key;
2307 }
2308 }
2309
2310 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2311 public Map.Entry<K,V> next() {
2312 Node<K,V> n = next;
2313 V v = nextValue;
2314 advance();
2315 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2316 }
2317 }
2318
2319 /* ---------------- View Classes -------------- */
2320
2321 /*
2322 * View classes are static, delegating to a ConcurrentNavigableMap
2323 * to allow use by SubMaps, which outweighs the ugliness of
2324 * needing type-tests for Iterator methods.
2325 */
2326
2327 static final <E> List<E> toList(Collection<E> c) {
2328 // Using size() here would be a pessimization.
2329 ArrayList<E> list = new ArrayList<E>();
2330 for (E e : c)
2331 list.add(e);
2332 return list;
2333 }
2334
2335 static final class KeySet<K,V>
2336 extends AbstractSet<K> implements NavigableSet<K> {
2337 final ConcurrentNavigableMap<K,V> m;
2338 KeySet(ConcurrentNavigableMap<K,V> map) { m = map; }
2339 public int size() { return m.size(); }
2340 public boolean isEmpty() { return m.isEmpty(); }
2341 public boolean contains(Object o) { return m.containsKey(o); }
2342 public boolean remove(Object o) { return m.remove(o) != null; }
2343 public void clear() { m.clear(); }
2344 public K lower(K e) { return m.lowerKey(e); }
2345 public K floor(K e) { return m.floorKey(e); }
2346 public K ceiling(K e) { return m.ceilingKey(e); }
2347 public K higher(K e) { return m.higherKey(e); }
2348 public Comparator<? super K> comparator() { return m.comparator(); }
2349 public K first() { return m.firstKey(); }
2350 public K last() { return m.lastKey(); }
2351 public K pollFirst() {
2352 Map.Entry<K,V> e = m.pollFirstEntry();
2353 return (e == null) ? null : e.getKey();
2354 }
2355 public K pollLast() {
2356 Map.Entry<K,V> e = m.pollLastEntry();
2357 return (e == null) ? null : e.getKey();
2358 }
2359 public Iterator<K> iterator() {
2360 return (m instanceof ConcurrentSkipListMap)
2361 ? ((ConcurrentSkipListMap<K,V>)m).new KeyIterator()
2362 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2363 }
2364 public boolean equals(Object o) {
2365 if (o == this)
2366 return true;
2367 if (!(o instanceof Set))
2368 return false;
2369 Collection<?> c = (Collection<?>) o;
2370 try {
2371 return containsAll(c) && c.containsAll(this);
2372 } catch (ClassCastException unused) {
2373 return false;
2374 } catch (NullPointerException unused) {
2375 return false;
2376 }
2377 }
2378 public Object[] toArray() { return toList(this).toArray(); }
2379 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2380 public Iterator<K> descendingIterator() {
2381 return descendingSet().iterator();
2382 }
2383 public NavigableSet<K> subSet(K fromElement,
2384 boolean fromInclusive,
2385 K toElement,
2386 boolean toInclusive) {
2387 return new KeySet<>(m.subMap(fromElement, fromInclusive,
2388 toElement, toInclusive));
2389 }
2390 public NavigableSet<K> headSet(K toElement, boolean inclusive) {
2391 return new KeySet<>(m.headMap(toElement, inclusive));
2392 }
2393 public NavigableSet<K> tailSet(K fromElement, boolean inclusive) {
2394 return new KeySet<>(m.tailMap(fromElement, inclusive));
2395 }
2396 public NavigableSet<K> subSet(K fromElement, K toElement) {
2397 return subSet(fromElement, true, toElement, false);
2398 }
2399 public NavigableSet<K> headSet(K toElement) {
2400 return headSet(toElement, false);
2401 }
2402 public NavigableSet<K> tailSet(K fromElement) {
2403 return tailSet(fromElement, true);
2404 }
2405 public NavigableSet<K> descendingSet() {
2406 return new KeySet<>(m.descendingMap());
2407 }
2408
2409 public Spliterator<K> spliterator() {
2410 return (m instanceof ConcurrentSkipListMap)
2411 ? ((ConcurrentSkipListMap<K,V>)m).keySpliterator()
2412 : ((SubMap<K,V>)m).new SubMapKeyIterator();
2413 }
2414 }
2415
2416 static final class Values<K,V> extends AbstractCollection<V> {
2417 final ConcurrentNavigableMap<K,V> m;
2418 Values(ConcurrentNavigableMap<K,V> map) {
2419 m = map;
2420 }
2421 public Iterator<V> iterator() {
2422 return (m instanceof ConcurrentSkipListMap)
2423 ? ((ConcurrentSkipListMap<K,V>)m).new ValueIterator()
2424 : ((SubMap<K,V>)m).new SubMapValueIterator();
2425 }
2426 public int size() { return m.size(); }
2427 public boolean isEmpty() { return m.isEmpty(); }
2428 public boolean contains(Object o) { return m.containsValue(o); }
2429 public void clear() { m.clear(); }
2430 public Object[] toArray() { return toList(this).toArray(); }
2431 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2432
2433 public Spliterator<V> spliterator() {
2434 return (m instanceof ConcurrentSkipListMap)
2435 ? ((ConcurrentSkipListMap<K,V>)m).valueSpliterator()
2436 : ((SubMap<K,V>)m).new SubMapValueIterator();
2437 }
2438
2439 public boolean removeIf(Predicate<? super V> filter) {
2440 if (filter == null) throw new NullPointerException();
2441 if (m instanceof ConcurrentSkipListMap)
2442 return ((ConcurrentSkipListMap<K,V>)m).removeValueIf(filter);
2443 // else use iterator
2444 Iterator<Map.Entry<K,V>> it =
2445 ((SubMap<K,V>)m).new SubMapEntryIterator();
2446 boolean removed = false;
2447 while (it.hasNext()) {
2448 Map.Entry<K,V> e = it.next();
2449 V v = e.getValue();
2450 if (filter.test(v) && m.remove(e.getKey(), v))
2451 removed = true;
2452 }
2453 return removed;
2454 }
2455 }
2456
2457 static final class EntrySet<K,V> extends AbstractSet<Map.Entry<K,V>> {
2458 final ConcurrentNavigableMap<K,V> m;
2459 EntrySet(ConcurrentNavigableMap<K,V> map) {
2460 m = map;
2461 }
2462 public Iterator<Map.Entry<K,V>> iterator() {
2463 return (m instanceof ConcurrentSkipListMap)
2464 ? ((ConcurrentSkipListMap<K,V>)m).new EntryIterator()
2465 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2466 }
2467
2468 public boolean contains(Object o) {
2469 if (!(o instanceof Map.Entry))
2470 return false;
2471 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2472 V v = m.get(e.getKey());
2473 return v != null && v.equals(e.getValue());
2474 }
2475 public boolean remove(Object o) {
2476 if (!(o instanceof Map.Entry))
2477 return false;
2478 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2479 return m.remove(e.getKey(),
2480 e.getValue());
2481 }
2482 public boolean isEmpty() {
2483 return m.isEmpty();
2484 }
2485 public int size() {
2486 return m.size();
2487 }
2488 public void clear() {
2489 m.clear();
2490 }
2491 public boolean equals(Object o) {
2492 if (o == this)
2493 return true;
2494 if (!(o instanceof Set))
2495 return false;
2496 Collection<?> c = (Collection<?>) o;
2497 try {
2498 return containsAll(c) && c.containsAll(this);
2499 } catch (ClassCastException unused) {
2500 return false;
2501 } catch (NullPointerException unused) {
2502 return false;
2503 }
2504 }
2505 public Object[] toArray() { return toList(this).toArray(); }
2506 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2507
2508 public Spliterator<Map.Entry<K,V>> spliterator() {
2509 return (m instanceof ConcurrentSkipListMap)
2510 ? ((ConcurrentSkipListMap<K,V>)m).entrySpliterator()
2511 : ((SubMap<K,V>)m).new SubMapEntryIterator();
2512 }
2513 public boolean removeIf(Predicate<? super Entry<K,V>> filter) {
2514 if (filter == null) throw new NullPointerException();
2515 if (m instanceof ConcurrentSkipListMap)
2516 return ((ConcurrentSkipListMap<K,V>)m).removeEntryIf(filter);
2517 // else use iterator
2518 Iterator<Map.Entry<K,V>> it =
2519 ((SubMap<K,V>)m).new SubMapEntryIterator();
2520 boolean removed = false;
2521 while (it.hasNext()) {
2522 Map.Entry<K,V> e = it.next();
2523 if (filter.test(e) && m.remove(e.getKey(), e.getValue()))
2524 removed = true;
2525 }
2526 return removed;
2527 }
2528 }
2529
2530 /**
2531 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2532 * represent a subrange of mappings of their underlying maps.
2533 * Instances of this class support all methods of their underlying
2534 * maps, differing in that mappings outside their range are ignored,
2535 * and attempts to add mappings outside their ranges result in {@link
2536 * IllegalArgumentException}. Instances of this class are constructed
2537 * only using the {@code subMap}, {@code headMap}, and {@code tailMap}
2538 * methods of their underlying maps.
2539 *
2540 * @serial include
2541 */
2542 static final class SubMap<K,V> extends AbstractMap<K,V>
2543 implements ConcurrentNavigableMap<K,V>, Serializable {
2544 private static final long serialVersionUID = -7647078645895051609L;
2545
2546 /** Underlying map */
2547 final ConcurrentSkipListMap<K,V> m;
2548 /** lower bound key, or null if from start */
2549 private final K lo;
2550 /** upper bound key, or null if to end */
2551 private final K hi;
2552 /** inclusion flag for lo */
2553 private final boolean loInclusive;
2554 /** inclusion flag for hi */
2555 private final boolean hiInclusive;
2556 /** direction */
2557 final boolean isDescending;
2558
2559 // Lazily initialized view holders
2560 private transient KeySet<K,V> keySetView;
2561 private transient Values<K,V> valuesView;
2562 private transient EntrySet<K,V> entrySetView;
2563
2564 /**
2565 * Creates a new submap, initializing all fields.
2566 */
2567 SubMap(ConcurrentSkipListMap<K,V> map,
2568 K fromKey, boolean fromInclusive,
2569 K toKey, boolean toInclusive,
2570 boolean isDescending) {
2571 Comparator<? super K> cmp = map.comparator;
2572 if (fromKey != null && toKey != null &&
2573 cpr(cmp, fromKey, toKey) > 0)
2574 throw new IllegalArgumentException("inconsistent range");
2575 this.m = map;
2576 this.lo = fromKey;
2577 this.hi = toKey;
2578 this.loInclusive = fromInclusive;
2579 this.hiInclusive = toInclusive;
2580 this.isDescending = isDescending;
2581 }
2582
2583 /* ---------------- Utilities -------------- */
2584
2585 boolean tooLow(Object key, Comparator<? super K> cmp) {
2586 int c;
2587 return (lo != null && ((c = cpr(cmp, key, lo)) < 0 ||
2588 (c == 0 && !loInclusive)));
2589 }
2590
2591 boolean tooHigh(Object key, Comparator<? super K> cmp) {
2592 int c;
2593 return (hi != null && ((c = cpr(cmp, key, hi)) > 0 ||
2594 (c == 0 && !hiInclusive)));
2595 }
2596
2597 boolean inBounds(Object key, Comparator<? super K> cmp) {
2598 return !tooLow(key, cmp) && !tooHigh(key, cmp);
2599 }
2600
2601 void checkKeyBounds(K key, Comparator<? super K> cmp) {
2602 if (key == null)
2603 throw new NullPointerException();
2604 if (!inBounds(key, cmp))
2605 throw new IllegalArgumentException("key out of range");
2606 }
2607
2608 /**
2609 * Returns true if node key is less than upper bound of range.
2610 */
2611 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n,
2612 Comparator<? super K> cmp) {
2613 if (n == null)
2614 return false;
2615 if (hi == null)
2616 return true;
2617 K k = n.key;
2618 if (k == null) // pass by markers and headers
2619 return true;
2620 int c = cpr(cmp, k, hi);
2621 if (c > 0 || (c == 0 && !hiInclusive))
2622 return false;
2623 return true;
2624 }
2625
2626 /**
2627 * Returns lowest node. This node might not be in range, so
2628 * most usages need to check bounds.
2629 */
2630 ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) {
2631 if (lo == null)
2632 return m.findFirst();
2633 else if (loInclusive)
2634 return m.findNear(lo, GT|EQ, cmp);
2635 else
2636 return m.findNear(lo, GT, cmp);
2637 }
2638
2639 /**
2640 * Returns highest node. This node might not be in range, so
2641 * most usages need to check bounds.
2642 */
2643 ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) {
2644 if (hi == null)
2645 return m.findLast();
2646 else if (hiInclusive)
2647 return m.findNear(hi, LT|EQ, cmp);
2648 else
2649 return m.findNear(hi, LT, cmp);
2650 }
2651
2652 /**
2653 * Returns lowest absolute key (ignoring directionality).
2654 */
2655 K lowestKey() {
2656 Comparator<? super K> cmp = m.comparator;
2657 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2658 if (isBeforeEnd(n, cmp))
2659 return n.key;
2660 else
2661 throw new NoSuchElementException();
2662 }
2663
2664 /**
2665 * Returns highest absolute key (ignoring directionality).
2666 */
2667 K highestKey() {
2668 Comparator<? super K> cmp = m.comparator;
2669 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2670 if (n != null) {
2671 K last = n.key;
2672 if (inBounds(last, cmp))
2673 return last;
2674 }
2675 throw new NoSuchElementException();
2676 }
2677
2678 Map.Entry<K,V> lowestEntry() {
2679 Comparator<? super K> cmp = m.comparator;
2680 for (;;) {
2681 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2682 if (!isBeforeEnd(n, cmp))
2683 return null;
2684 Map.Entry<K,V> e = n.createSnapshot();
2685 if (e != null)
2686 return e;
2687 }
2688 }
2689
2690 Map.Entry<K,V> highestEntry() {
2691 Comparator<? super K> cmp = m.comparator;
2692 for (;;) {
2693 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2694 if (n == null || !inBounds(n.key, cmp))
2695 return null;
2696 Map.Entry<K,V> e = n.createSnapshot();
2697 if (e != null)
2698 return e;
2699 }
2700 }
2701
2702 Map.Entry<K,V> removeLowest() {
2703 Comparator<? super K> cmp = m.comparator;
2704 for (;;) {
2705 Node<K,V> n = loNode(cmp);
2706 if (n == null)
2707 return null;
2708 K k = n.key;
2709 if (!inBounds(k, cmp))
2710 return null;
2711 V v = m.doRemove(k, null);
2712 if (v != null)
2713 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2714 }
2715 }
2716
2717 Map.Entry<K,V> removeHighest() {
2718 Comparator<? super K> cmp = m.comparator;
2719 for (;;) {
2720 Node<K,V> n = hiNode(cmp);
2721 if (n == null)
2722 return null;
2723 K k = n.key;
2724 if (!inBounds(k, cmp))
2725 return null;
2726 V v = m.doRemove(k, null);
2727 if (v != null)
2728 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2729 }
2730 }
2731
2732 /**
2733 * Submap version of ConcurrentSkipListMap.getNearEntry.
2734 */
2735 Map.Entry<K,V> getNearEntry(K key, int rel) {
2736 Comparator<? super K> cmp = m.comparator;
2737 if (isDescending) { // adjust relation for direction
2738 if ((rel & LT) == 0)
2739 rel |= LT;
2740 else
2741 rel &= ~LT;
2742 }
2743 if (tooLow(key, cmp))
2744 return ((rel & LT) != 0) ? null : lowestEntry();
2745 if (tooHigh(key, cmp))
2746 return ((rel & LT) != 0) ? highestEntry() : null;
2747 for (;;) {
2748 Node<K,V> n = m.findNear(key, rel, cmp);
2749 if (n == null || !inBounds(n.key, cmp))
2750 return null;
2751 K k = n.key;
2752 V v = n.getValidValue();
2753 if (v != null)
2754 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2755 }
2756 }
2757
2758 // Almost the same as getNearEntry, except for keys
2759 K getNearKey(K key, int rel) {
2760 Comparator<? super K> cmp = m.comparator;
2761 if (isDescending) { // adjust relation for direction
2762 if ((rel & LT) == 0)
2763 rel |= LT;
2764 else
2765 rel &= ~LT;
2766 }
2767 if (tooLow(key, cmp)) {
2768 if ((rel & LT) == 0) {
2769 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2770 if (isBeforeEnd(n, cmp))
2771 return n.key;
2772 }
2773 return null;
2774 }
2775 if (tooHigh(key, cmp)) {
2776 if ((rel & LT) != 0) {
2777 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2778 if (n != null) {
2779 K last = n.key;
2780 if (inBounds(last, cmp))
2781 return last;
2782 }
2783 }
2784 return null;
2785 }
2786 for (;;) {
2787 Node<K,V> n = m.findNear(key, rel, cmp);
2788 if (n == null || !inBounds(n.key, cmp))
2789 return null;
2790 K k = n.key;
2791 V v = n.getValidValue();
2792 if (v != null)
2793 return k;
2794 }
2795 }
2796
2797 /* ---------------- Map API methods -------------- */
2798
2799 public boolean containsKey(Object key) {
2800 if (key == null) throw new NullPointerException();
2801 return inBounds(key, m.comparator) && m.containsKey(key);
2802 }
2803
2804 public V get(Object key) {
2805 if (key == null) throw new NullPointerException();
2806 return (!inBounds(key, m.comparator)) ? null : m.get(key);
2807 }
2808
2809 public V put(K key, V value) {
2810 checkKeyBounds(key, m.comparator);
2811 return m.put(key, value);
2812 }
2813
2814 public V remove(Object key) {
2815 return (!inBounds(key, m.comparator)) ? null : m.remove(key);
2816 }
2817
2818 public int size() {
2819 Comparator<? super K> cmp = m.comparator;
2820 long count = 0;
2821 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2822 isBeforeEnd(n, cmp);
2823 n = n.next) {
2824 if (n.getValidValue() != null)
2825 ++count;
2826 }
2827 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2828 }
2829
2830 public boolean isEmpty() {
2831 Comparator<? super K> cmp = m.comparator;
2832 return !isBeforeEnd(loNode(cmp), cmp);
2833 }
2834
2835 public boolean containsValue(Object value) {
2836 if (value == null)
2837 throw new NullPointerException();
2838 Comparator<? super K> cmp = m.comparator;
2839 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2840 isBeforeEnd(n, cmp);
2841 n = n.next) {
2842 V v = n.getValidValue();
2843 if (v != null && value.equals(v))
2844 return true;
2845 }
2846 return false;
2847 }
2848
2849 public void clear() {
2850 Comparator<? super K> cmp = m.comparator;
2851 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2852 isBeforeEnd(n, cmp);
2853 n = n.next) {
2854 if (n.getValidValue() != null)
2855 m.remove(n.key);
2856 }
2857 }
2858
2859 /* ---------------- ConcurrentMap API methods -------------- */
2860
2861 public V putIfAbsent(K key, V value) {
2862 checkKeyBounds(key, m.comparator);
2863 return m.putIfAbsent(key, value);
2864 }
2865
2866 public boolean remove(Object key, Object value) {
2867 return inBounds(key, m.comparator) && m.remove(key, value);
2868 }
2869
2870 public boolean replace(K key, V oldValue, V newValue) {
2871 checkKeyBounds(key, m.comparator);
2872 return m.replace(key, oldValue, newValue);
2873 }
2874
2875 public V replace(K key, V value) {
2876 checkKeyBounds(key, m.comparator);
2877 return m.replace(key, value);
2878 }
2879
2880 /* ---------------- SortedMap API methods -------------- */
2881
2882 public Comparator<? super K> comparator() {
2883 Comparator<? super K> cmp = m.comparator();
2884 if (isDescending)
2885 return Collections.reverseOrder(cmp);
2886 else
2887 return cmp;
2888 }
2889
2890 /**
2891 * Utility to create submaps, where given bounds override
2892 * unbounded(null) ones and/or are checked against bounded ones.
2893 */
2894 SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive,
2895 K toKey, boolean toInclusive) {
2896 Comparator<? super K> cmp = m.comparator;
2897 if (isDescending) { // flip senses
2898 K tk = fromKey;
2899 fromKey = toKey;
2900 toKey = tk;
2901 boolean ti = fromInclusive;
2902 fromInclusive = toInclusive;
2903 toInclusive = ti;
2904 }
2905 if (lo != null) {
2906 if (fromKey == null) {
2907 fromKey = lo;
2908 fromInclusive = loInclusive;
2909 }
2910 else {
2911 int c = cpr(cmp, fromKey, lo);
2912 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2913 throw new IllegalArgumentException("key out of range");
2914 }
2915 }
2916 if (hi != null) {
2917 if (toKey == null) {
2918 toKey = hi;
2919 toInclusive = hiInclusive;
2920 }
2921 else {
2922 int c = cpr(cmp, toKey, hi);
2923 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2924 throw new IllegalArgumentException("key out of range");
2925 }
2926 }
2927 return new SubMap<K,V>(m, fromKey, fromInclusive,
2928 toKey, toInclusive, isDescending);
2929 }
2930
2931 public SubMap<K,V> subMap(K fromKey, boolean fromInclusive,
2932 K toKey, boolean toInclusive) {
2933 if (fromKey == null || toKey == null)
2934 throw new NullPointerException();
2935 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2936 }
2937
2938 public SubMap<K,V> headMap(K toKey, boolean inclusive) {
2939 if (toKey == null)
2940 throw new NullPointerException();
2941 return newSubMap(null, false, toKey, inclusive);
2942 }
2943
2944 public SubMap<K,V> tailMap(K fromKey, boolean inclusive) {
2945 if (fromKey == null)
2946 throw new NullPointerException();
2947 return newSubMap(fromKey, inclusive, null, false);
2948 }
2949
2950 public SubMap<K,V> subMap(K fromKey, K toKey) {
2951 return subMap(fromKey, true, toKey, false);
2952 }
2953
2954 public SubMap<K,V> headMap(K toKey) {
2955 return headMap(toKey, false);
2956 }
2957
2958 public SubMap<K,V> tailMap(K fromKey) {
2959 return tailMap(fromKey, true);
2960 }
2961
2962 public SubMap<K,V> descendingMap() {
2963 return new SubMap<K,V>(m, lo, loInclusive,
2964 hi, hiInclusive, !isDescending);
2965 }
2966
2967 /* ---------------- Relational methods -------------- */
2968
2969 public Map.Entry<K,V> ceilingEntry(K key) {
2970 return getNearEntry(key, GT|EQ);
2971 }
2972
2973 public K ceilingKey(K key) {
2974 return getNearKey(key, GT|EQ);
2975 }
2976
2977 public Map.Entry<K,V> lowerEntry(K key) {
2978 return getNearEntry(key, LT);
2979 }
2980
2981 public K lowerKey(K key) {
2982 return getNearKey(key, LT);
2983 }
2984
2985 public Map.Entry<K,V> floorEntry(K key) {
2986 return getNearEntry(key, LT|EQ);
2987 }
2988
2989 public K floorKey(K key) {
2990 return getNearKey(key, LT|EQ);
2991 }
2992
2993 public Map.Entry<K,V> higherEntry(K key) {
2994 return getNearEntry(key, GT);
2995 }
2996
2997 public K higherKey(K key) {
2998 return getNearKey(key, GT);
2999 }
3000
3001 public K firstKey() {
3002 return isDescending ? highestKey() : lowestKey();
3003 }
3004
3005 public K lastKey() {
3006 return isDescending ? lowestKey() : highestKey();
3007 }
3008
3009 public Map.Entry<K,V> firstEntry() {
3010 return isDescending ? highestEntry() : lowestEntry();
3011 }
3012
3013 public Map.Entry<K,V> lastEntry() {
3014 return isDescending ? lowestEntry() : highestEntry();
3015 }
3016
3017 public Map.Entry<K,V> pollFirstEntry() {
3018 return isDescending ? removeHighest() : removeLowest();
3019 }
3020
3021 public Map.Entry<K,V> pollLastEntry() {
3022 return isDescending ? removeLowest() : removeHighest();
3023 }
3024
3025 /* ---------------- Submap Views -------------- */
3026
3027 public NavigableSet<K> keySet() {
3028 KeySet<K,V> ks;
3029 if ((ks = keySetView) != null) return ks;
3030 return keySetView = new KeySet<>(this);
3031 }
3032
3033 public NavigableSet<K> navigableKeySet() {
3034 KeySet<K,V> ks;
3035 if ((ks = keySetView) != null) return ks;
3036 return keySetView = new KeySet<>(this);
3037 }
3038
3039 public Collection<V> values() {
3040 Values<K,V> vs;
3041 if ((vs = valuesView) != null) return vs;
3042 return valuesView = new Values<>(this);
3043 }
3044
3045 public Set<Map.Entry<K,V>> entrySet() {
3046 EntrySet<K,V> es;
3047 if ((es = entrySetView) != null) return es;
3048 return entrySetView = new EntrySet<K,V>(this);
3049 }
3050
3051 public NavigableSet<K> descendingKeySet() {
3052 return descendingMap().navigableKeySet();
3053 }
3054
3055 /**
3056 * Variant of main Iter class to traverse through submaps.
3057 * Also serves as back-up Spliterator for views.
3058 */
3059 abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> {
3060 /** the last node returned by next() */
3061 Node<K,V> lastReturned;
3062 /** the next node to return from next(); */
3063 Node<K,V> next;
3064 /** Cache of next value field to maintain weak consistency */
3065 V nextValue;
3066
3067 SubMapIter() {
3068 Comparator<? super K> cmp = m.comparator;
3069 for (;;) {
3070 next = isDescending ? hiNode(cmp) : loNode(cmp);
3071 if (next == null)
3072 break;
3073 Object x = next.value;
3074 if (x != null && x != next) {
3075 if (! inBounds(next.key, cmp))
3076 next = null;
3077 else {
3078 @SuppressWarnings("unchecked") V vv = (V)x;
3079 nextValue = vv;
3080 }
3081 break;
3082 }
3083 }
3084 }
3085
3086 public final boolean hasNext() {
3087 return next != null;
3088 }
3089
3090 final void advance() {
3091 if (next == null)
3092 throw new NoSuchElementException();
3093 lastReturned = next;
3094 if (isDescending)
3095 descend();
3096 else
3097 ascend();
3098 }
3099
3100 private void ascend() {
3101 Comparator<? super K> cmp = m.comparator;
3102 for (;;) {
3103 next = next.next;
3104 if (next == null)
3105 break;
3106 Object x = next.value;
3107 if (x != null && x != next) {
3108 if (tooHigh(next.key, cmp))
3109 next = null;
3110 else {
3111 @SuppressWarnings("unchecked") V vv = (V)x;
3112 nextValue = vv;
3113 }
3114 break;
3115 }
3116 }
3117 }
3118
3119 private void descend() {
3120 Comparator<? super K> cmp = m.comparator;
3121 for (;;) {
3122 next = m.findNear(lastReturned.key, LT, cmp);
3123 if (next == null)
3124 break;
3125 Object x = next.value;
3126 if (x != null && x != next) {
3127 if (tooLow(next.key, cmp))
3128 next = null;
3129 else {
3130 @SuppressWarnings("unchecked") V vv = (V)x;
3131 nextValue = vv;
3132 }
3133 break;
3134 }
3135 }
3136 }
3137
3138 public void remove() {
3139 Node<K,V> l = lastReturned;
3140 if (l == null)
3141 throw new IllegalStateException();
3142 m.remove(l.key);
3143 lastReturned = null;
3144 }
3145
3146 public Spliterator<T> trySplit() {
3147 return null;
3148 }
3149
3150 public boolean tryAdvance(Consumer<? super T> action) {
3151 if (hasNext()) {
3152 action.accept(next());
3153 return true;
3154 }
3155 return false;
3156 }
3157
3158 public void forEachRemaining(Consumer<? super T> action) {
3159 while (hasNext())
3160 action.accept(next());
3161 }
3162
3163 public long estimateSize() {
3164 return Long.MAX_VALUE;
3165 }
3166
3167 }
3168
3169 final class SubMapValueIterator extends SubMapIter<V> {
3170 public V next() {
3171 V v = nextValue;
3172 advance();
3173 return v;
3174 }
3175 public int characteristics() {
3176 return 0;
3177 }
3178 }
3179
3180 final class SubMapKeyIterator extends SubMapIter<K> {
3181 public K next() {
3182 Node<K,V> n = next;
3183 advance();
3184 return n.key;
3185 }
3186 public int characteristics() {
3187 return Spliterator.DISTINCT | Spliterator.ORDERED |
3188 Spliterator.SORTED;
3189 }
3190 public final Comparator<? super K> getComparator() {
3191 return SubMap.this.comparator();
3192 }
3193 }
3194
3195 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3196 public Map.Entry<K,V> next() {
3197 Node<K,V> n = next;
3198 V v = nextValue;
3199 advance();
3200 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3201 }
3202 public int characteristics() {
3203 return Spliterator.DISTINCT;
3204 }
3205 }
3206 }
3207
3208 // default Map method overrides
3209
3210 public void forEach(BiConsumer<? super K, ? super V> action) {
3211 if (action == null) throw new NullPointerException();
3212 V v;
3213 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3214 if ((v = n.getValidValue()) != null)
3215 action.accept(n.key, v);
3216 }
3217 }
3218
3219 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3220 if (function == null) throw new NullPointerException();
3221 V v;
3222 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3223 while ((v = n.getValidValue()) != null) {
3224 V r = function.apply(n.key, v);
3225 if (r == null) throw new NullPointerException();
3226 if (n.casValue(v, r))
3227 break;
3228 }
3229 }
3230 }
3231
3232 /**
3233 * Helper method for EntrySet.removeIf.
3234 */
3235 boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
3236 if (function == null) throw new NullPointerException();
3237 boolean removed = false;
3238 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3239 V v;
3240 if ((v = n.getValidValue()) != null) {
3241 K k = n.key;
3242 Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
3243 if (function.test(e) && remove(k, v))
3244 removed = true;
3245 }
3246 }
3247 return removed;
3248 }
3249
3250 /**
3251 * Helper method for Values.removeIf.
3252 */
3253 boolean removeValueIf(Predicate<? super V> function) {
3254 if (function == null) throw new NullPointerException();
3255 boolean removed = false;
3256 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3257 V v;
3258 if ((v = n.getValidValue()) != null) {
3259 K k = n.key;
3260 if (function.test(v) && remove(k, v))
3261 removed = true;
3262 }
3263 }
3264 return removed;
3265 }
3266
3267 /**
3268 * Base class providing common structure for Spliterators.
3269 * (Although not all that much common functionality; as usual for
3270 * view classes, details annoyingly vary in key, value, and entry
3271 * subclasses in ways that are not worth abstracting out for
3272 * internal classes.)
3273 *
3274 * The basic split strategy is to recursively descend from top
3275 * level, row by row, descending to next row when either split
3276 * off, or the end of row is encountered. Control of the number of
3277 * splits relies on some statistical estimation: The expected
3278 * remaining number of elements of a skip list when advancing
3279 * either across or down decreases by about 25%. To make this
3280 * observation useful, we need to know initial size, which we
3281 * don't. But we can just use Integer.MAX_VALUE so that we
3282 * don't prematurely zero out while splitting.
3283 */
3284 abstract static class CSLMSpliterator<K,V> {
3285 final Comparator<? super K> comparator;
3286 final K fence; // exclusive upper bound for keys, or null if to end
3287 Index<K,V> row; // the level to split out
3288 Node<K,V> current; // current traversal node; initialize at origin
3289 int est; // pseudo-size estimate
3290 CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3291 Node<K,V> origin, K fence, int est) {
3292 this.comparator = comparator; this.row = row;
3293 this.current = origin; this.fence = fence; this.est = est;
3294 }
3295
3296 public final long estimateSize() { return (long)est; }
3297 }
3298
3299 static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
3300 implements Spliterator<K> {
3301 KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3302 Node<K,V> origin, K fence, int est) {
3303 super(comparator, row, origin, fence, est);
3304 }
3305
3306 public KeySpliterator<K,V> trySplit() {
3307 Node<K,V> e; K ek;
3308 Comparator<? super K> cmp = comparator;
3309 K f = fence;
3310 if ((e = current) != null && (ek = e.key) != null) {
3311 for (Index<K,V> q = row; q != null; q = row = q.down) {
3312 Index<K,V> s; Node<K,V> b, n; K sk;
3313 if ((s = q.right) != null && (b = s.node) != null &&
3314 (n = b.next) != null && n.value != null &&
3315 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3316 (f == null || cpr(cmp, sk, f) < 0)) {
3317 current = n;
3318 Index<K,V> r = q.down;
3319 row = (s.right != null) ? s : s.down;
3320 est -= est >>> 2;
3321 return new KeySpliterator<K,V>(cmp, r, e, sk, est);
3322 }
3323 }
3324 }
3325 return null;
3326 }
3327
3328 public void forEachRemaining(Consumer<? super K> action) {
3329 if (action == null) throw new NullPointerException();
3330 Comparator<? super K> cmp = comparator;
3331 K f = fence;
3332 Node<K,V> e = current;
3333 current = null;
3334 for (; e != null; e = e.next) {
3335 K k; Object v;
3336 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3337 break;
3338 if ((v = e.value) != null && v != e)
3339 action.accept(k);
3340 }
3341 }
3342
3343 public boolean tryAdvance(Consumer<? super K> action) {
3344 if (action == null) throw new NullPointerException();
3345 Comparator<? super K> cmp = comparator;
3346 K f = fence;
3347 Node<K,V> e = current;
3348 for (; e != null; e = e.next) {
3349 K k; Object v;
3350 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3351 e = null;
3352 break;
3353 }
3354 if ((v = e.value) != null && v != e) {
3355 current = e.next;
3356 action.accept(k);
3357 return true;
3358 }
3359 }
3360 current = e;
3361 return false;
3362 }
3363
3364 public int characteristics() {
3365 return Spliterator.DISTINCT | Spliterator.SORTED |
3366 Spliterator.ORDERED | Spliterator.CONCURRENT |
3367 Spliterator.NONNULL;
3368 }
3369
3370 public final Comparator<? super K> getComparator() {
3371 return comparator;
3372 }
3373 }
3374 // factory method for KeySpliterator
3375 final KeySpliterator<K,V> keySpliterator() {
3376 Comparator<? super K> cmp = comparator;
3377 for (;;) { // ensure h corresponds to origin p
3378 HeadIndex<K,V> h; Node<K,V> p;
3379 Node<K,V> b = (h = head).node;
3380 if ((p = b.next) == null || p.value != null)
3381 return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3382 0 : Integer.MAX_VALUE);
3383 p.helpDelete(b, p.next);
3384 }
3385 }
3386
3387 static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
3388 implements Spliterator<V> {
3389 ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3390 Node<K,V> origin, K fence, int est) {
3391 super(comparator, row, origin, fence, est);
3392 }
3393
3394 public ValueSpliterator<K,V> trySplit() {
3395 Node<K,V> e; K ek;
3396 Comparator<? super K> cmp = comparator;
3397 K f = fence;
3398 if ((e = current) != null && (ek = e.key) != null) {
3399 for (Index<K,V> q = row; q != null; q = row = q.down) {
3400 Index<K,V> s; Node<K,V> b, n; K sk;
3401 if ((s = q.right) != null && (b = s.node) != null &&
3402 (n = b.next) != null && n.value != null &&
3403 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3404 (f == null || cpr(cmp, sk, f) < 0)) {
3405 current = n;
3406 Index<K,V> r = q.down;
3407 row = (s.right != null) ? s : s.down;
3408 est -= est >>> 2;
3409 return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
3410 }
3411 }
3412 }
3413 return null;
3414 }
3415
3416 public void forEachRemaining(Consumer<? super V> action) {
3417 if (action == null) throw new NullPointerException();
3418 Comparator<? super K> cmp = comparator;
3419 K f = fence;
3420 Node<K,V> e = current;
3421 current = null;
3422 for (; e != null; e = e.next) {
3423 K k; Object v;
3424 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3425 break;
3426 if ((v = e.value) != null && v != e) {
3427 @SuppressWarnings("unchecked") V vv = (V)v;
3428 action.accept(vv);
3429 }
3430 }
3431 }
3432
3433 public boolean tryAdvance(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 for (; e != null; e = e.next) {
3439 K k; Object v;
3440 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3441 e = null;
3442 break;
3443 }
3444 if ((v = e.value) != null && v != e) {
3445 current = e.next;
3446 @SuppressWarnings("unchecked") V vv = (V)v;
3447 action.accept(vv);
3448 return true;
3449 }
3450 }
3451 current = e;
3452 return false;
3453 }
3454
3455 public int characteristics() {
3456 return Spliterator.CONCURRENT | Spliterator.ORDERED |
3457 Spliterator.NONNULL;
3458 }
3459 }
3460
3461 // Almost the same as keySpliterator()
3462 final ValueSpliterator<K,V> valueSpliterator() {
3463 Comparator<? super K> cmp = comparator;
3464 for (;;) {
3465 HeadIndex<K,V> h; Node<K,V> p;
3466 Node<K,V> b = (h = head).node;
3467 if ((p = b.next) == null || p.value != null)
3468 return new ValueSpliterator<K,V>(cmp, h, p, null, (p == null) ?
3469 0 : Integer.MAX_VALUE);
3470 p.helpDelete(b, p.next);
3471 }
3472 }
3473
3474 static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
3475 implements Spliterator<Map.Entry<K,V>> {
3476 EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3477 Node<K,V> origin, K fence, int est) {
3478 super(comparator, row, origin, fence, est);
3479 }
3480
3481 public EntrySpliterator<K,V> trySplit() {
3482 Node<K,V> e; K ek;
3483 Comparator<? super K> cmp = comparator;
3484 K f = fence;
3485 if ((e = current) != null && (ek = e.key) != null) {
3486 for (Index<K,V> q = row; q != null; q = row = q.down) {
3487 Index<K,V> s; Node<K,V> b, n; K sk;
3488 if ((s = q.right) != null && (b = s.node) != null &&
3489 (n = b.next) != null && n.value != null &&
3490 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3491 (f == null || cpr(cmp, sk, f) < 0)) {
3492 current = n;
3493 Index<K,V> r = q.down;
3494 row = (s.right != null) ? s : s.down;
3495 est -= est >>> 2;
3496 return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
3497 }
3498 }
3499 }
3500 return null;
3501 }
3502
3503 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3504 if (action == null) throw new NullPointerException();
3505 Comparator<? super K> cmp = comparator;
3506 K f = fence;
3507 Node<K,V> e = current;
3508 current = null;
3509 for (; e != null; e = e.next) {
3510 K k; Object v;
3511 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3512 break;
3513 if ((v = e.value) != null && v != e) {
3514 @SuppressWarnings("unchecked") V vv = (V)v;
3515 action.accept
3516 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3517 }
3518 }
3519 }
3520
3521 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3522 if (action == null) throw new NullPointerException();
3523 Comparator<? super K> cmp = comparator;
3524 K f = fence;
3525 Node<K,V> e = current;
3526 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 e = null;
3530 break;
3531 }
3532 if ((v = e.value) != null && v != e) {
3533 current = e.next;
3534 @SuppressWarnings("unchecked") V vv = (V)v;
3535 action.accept
3536 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3537 return true;
3538 }
3539 }
3540 current = e;
3541 return false;
3542 }
3543
3544 public int characteristics() {
3545 return Spliterator.DISTINCT | Spliterator.SORTED |
3546 Spliterator.ORDERED | Spliterator.CONCURRENT |
3547 Spliterator.NONNULL;
3548 }
3549
3550 public final Comparator<Map.Entry<K,V>> getComparator() {
3551 // Adapt or create a key-based comparator
3552 if (comparator != null) {
3553 return Map.Entry.comparingByKey(comparator);
3554 }
3555 else {
3556 return (Comparator<Map.Entry<K,V>> & Serializable) (e1, e2) -> {
3557 @SuppressWarnings("unchecked")
3558 Comparable<? super K> k1 = (Comparable<? super K>) e1.getKey();
3559 return k1.compareTo(e2.getKey());
3560 };
3561 }
3562 }
3563 }
3564
3565 // Almost the same as keySpliterator()
3566 final EntrySpliterator<K,V> entrySpliterator() {
3567 Comparator<? super K> cmp = comparator;
3568 for (;;) { // almost same as key version
3569 HeadIndex<K,V> h; Node<K,V> p;
3570 Node<K,V> b = (h = head).node;
3571 if ((p = b.next) == null || p.value != null)
3572 return new EntrySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3573 0 : Integer.MAX_VALUE);
3574 p.helpDelete(b, p.next);
3575 }
3576 }
3577
3578 // Unsafe mechanics
3579 private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
3580 private static final long HEAD;
3581 static {
3582 try {
3583 HEAD = U.objectFieldOffset
3584 (ConcurrentSkipListMap.class.getDeclaredField("head"));
3585 } catch (ReflectiveOperationException e) {
3586 throw new Error(e);
3587 }
3588 }
3589 }