ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.124
Committed: Sun Jun 16 14:48:11 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.123: +2 -2 lines
Log Message:
Merge should only put if absent

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