ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.138
Committed: Wed Dec 31 07:54:13 2014 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.137: +2 -1 lines
Log Message:
standardize import statement order

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