ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.112
Committed: Fri Mar 22 18:40:28 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.111: +2 -55 lines
Log Message:
Remove unneeded key set view methods

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