ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.119
Committed: Fri Apr 19 17:49:11 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.118: +1 -1 lines
Log Message:
modifier order

File Contents

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