ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.141
Committed: Sun Jan 4 09:15:11 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.140: +23 -29 lines
Log Message:
standardize Unsafe mechanics; slightly smaller bytecode

File Contents

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