ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.127
Committed: Mon Jul 1 19:08:00 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.126: +1 -2 lines
Log Message:
Sync with JDK

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.Iterator;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.NavigableMap;
19 import java.util.NavigableSet;
20 import java.util.NoSuchElementException;
21 import java.util.Set;
22 import java.util.SortedMap;
23 import java.util.SortedSet;
24 import java.util.Spliterator;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.ConcurrentNavigableMap;
27 import java.util.function.BiFunction;
28 import java.util.function.Consumer;
29 import java.util.function.BiConsumer;
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 * java.util.ConcurrentModificationException ConcurrentModificationException},
48 * and may proceed concurrently with other operations. Ascending key ordered
49 * views and their iterators 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 classes.)
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 = ThreadLocalRandom.nextSecondarySeed();
829 if ((rnd & 0x80000001) == 0) { // test highest and lowest bits
830 int level = 1, max;
831 while (((rnd >>>= 1) & 1) != 0)
832 ++level;
833 Index<K,V> idx = null;
834 HeadIndex<K,V> h = head;
835 if (level <= (max = h.level)) {
836 for (int i = 1; i <= level; ++i)
837 idx = new Index<K,V>(z, idx, null);
838 }
839 else { // try to grow by one level
840 level = max + 1; // hold in array and later pick the one to use
841 @SuppressWarnings("unchecked")Index<K,V>[] idxs =
842 (Index<K,V>[])new Index<?,?>[level+1];
843 for (int i = 1; i <= level; ++i)
844 idxs[i] = idx = new Index<K,V>(z, idx, null);
845 for (;;) {
846 h = head;
847 int oldLevel = h.level;
848 if (level <= oldLevel) // lost race to add level
849 break;
850 HeadIndex<K,V> newh = h;
851 Node<K,V> oldbase = h.node;
852 for (int j = oldLevel+1; j <= level; ++j)
853 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
854 if (casHead(h, newh)) {
855 h = newh;
856 idx = idxs[level = oldLevel];
857 break;
858 }
859 }
860 }
861 // find insertion points and splice in
862 splice: for (int insertionLevel = level;;) {
863 int j = h.level;
864 for (Index<K,V> q = h, r = q.right, t = idx;;) {
865 if (q == null || t == null)
866 break splice;
867 if (r != null) {
868 Node<K,V> n = r.node;
869 // compare before deletion check avoids needing recheck
870 int c = cpr(cmp, key, n.key);
871 if (n.value == null) {
872 if (!q.unlink(r))
873 break;
874 r = q.right;
875 continue;
876 }
877 if (c > 0) {
878 q = r;
879 r = r.right;
880 continue;
881 }
882 }
883
884 if (j == insertionLevel) {
885 if (!q.link(r, t))
886 break; // restart
887 if (t.node.value == null) {
888 findNode(key);
889 break splice;
890 }
891 if (--insertionLevel == 0)
892 break splice;
893 }
894
895 if (--j >= insertionLevel && j < level)
896 t = t.down;
897 q = q.down;
898 r = q.right;
899 }
900 }
901 }
902 return null;
903 }
904
905 /* ---------------- Deletion -------------- */
906
907 /**
908 * Main deletion method. Locates node, nulls value, appends a
909 * deletion marker, unlinks predecessor, removes associated index
910 * nodes, and possibly reduces head index level.
911 *
912 * Index nodes are cleared out simply by calling findPredecessor.
913 * which unlinks indexes to deleted nodes found along path to key,
914 * which will include the indexes to this node. This is done
915 * unconditionally. We can't check beforehand whether there are
916 * index nodes because it might be the case that some or all
917 * indexes hadn't been inserted yet for this node during initial
918 * search for it, and we'd like to ensure lack of garbage
919 * retention, so must call to be sure.
920 *
921 * @param key the key
922 * @param value if non-null, the value that must be
923 * associated with key
924 * @return the node, or null if not found
925 */
926 final V doRemove(Object key, Object value) {
927 if (key == null)
928 throw new NullPointerException();
929 Comparator<? super K> cmp = comparator;
930 outer: for (;;) {
931 for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
932 Object v; int c;
933 if (n == null)
934 break outer;
935 Node<K,V> f = n.next;
936 if (n != b.next) // inconsistent read
937 break;
938 if ((v = n.value) == null) { // n is deleted
939 n.helpDelete(b, f);
940 break;
941 }
942 if (b.value == null || v == n) // b is deleted
943 break;
944 if ((c = cpr(cmp, key, n.key)) < 0)
945 break outer;
946 if (c > 0) {
947 b = n;
948 n = f;
949 continue;
950 }
951 if (value != null && !value.equals(v))
952 break outer;
953 if (!n.casValue(v, null))
954 break;
955 if (!n.appendMarker(f) || !b.casNext(n, f))
956 findNode(key); // retry via findNode
957 else {
958 findPredecessor(key, cmp); // clean index
959 if (head.right == null)
960 tryReduceLevel();
961 }
962 @SuppressWarnings("unchecked") V vv = (V)v;
963 return vv;
964 }
965 }
966 return null;
967 }
968
969 /**
970 * Possibly reduce head level if it has no nodes. This method can
971 * (rarely) make mistakes, in which case levels can disappear even
972 * though they are about to contain index nodes. This impacts
973 * performance, not correctness. To minimize mistakes as well as
974 * to reduce hysteresis, the level is reduced by one only if the
975 * topmost three levels look empty. Also, if the removed level
976 * looks non-empty after CAS, we try to change it back quick
977 * before anyone notices our mistake! (This trick works pretty
978 * well because this method will practically never make mistakes
979 * unless current thread stalls immediately before first CAS, in
980 * which case it is very unlikely to stall again immediately
981 * afterwards, so will recover.)
982 *
983 * We put up with all this rather than just let levels grow
984 * because otherwise, even a small map that has undergone a large
985 * number of insertions and removals will have a lot of levels,
986 * slowing down access more than would an occasional unwanted
987 * reduction.
988 */
989 private void tryReduceLevel() {
990 HeadIndex<K,V> h = head;
991 HeadIndex<K,V> d;
992 HeadIndex<K,V> e;
993 if (h.level > 3 &&
994 (d = (HeadIndex<K,V>)h.down) != null &&
995 (e = (HeadIndex<K,V>)d.down) != null &&
996 e.right == null &&
997 d.right == null &&
998 h.right == null &&
999 casHead(h, d) && // try to set
1000 h.right != null) // recheck
1001 casHead(d, h); // try to backout
1002 }
1003
1004 /* ---------------- Finding and removing first element -------------- */
1005
1006 /**
1007 * Specialized variant of findNode to get first valid node.
1008 * @return first node or null if empty
1009 */
1010 final Node<K,V> findFirst() {
1011 for (Node<K,V> b, n;;) {
1012 if ((n = (b = head.node).next) == null)
1013 return null;
1014 if (n.value != null)
1015 return n;
1016 n.helpDelete(b, n.next);
1017 }
1018 }
1019
1020 /**
1021 * Removes first entry; returns its snapshot.
1022 * @return null if empty, else snapshot of first entry
1023 */
1024 private Map.Entry<K,V> doRemoveFirstEntry() {
1025 for (Node<K,V> b, n;;) {
1026 if ((n = (b = head.node).next) == null)
1027 return null;
1028 Node<K,V> f = n.next;
1029 if (n != b.next)
1030 continue;
1031 Object v = n.value;
1032 if (v == null) {
1033 n.helpDelete(b, f);
1034 continue;
1035 }
1036 if (!n.casValue(v, null))
1037 continue;
1038 if (!n.appendMarker(f) || !b.casNext(n, f))
1039 findFirst(); // retry
1040 clearIndexToFirst();
1041 @SuppressWarnings("unchecked") V vv = (V)v;
1042 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, vv);
1043 }
1044 }
1045
1046 /**
1047 * Clears out index nodes associated with deleted first entry.
1048 */
1049 private void clearIndexToFirst() {
1050 for (;;) {
1051 for (Index<K,V> q = head;;) {
1052 Index<K,V> r = q.right;
1053 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1054 break;
1055 if ((q = q.down) == null) {
1056 if (head.right == null)
1057 tryReduceLevel();
1058 return;
1059 }
1060 }
1061 }
1062 }
1063
1064 /**
1065 * Removes last entry; returns its snapshot.
1066 * Specialized variant of doRemove.
1067 * @return null if empty, else snapshot of last entry
1068 */
1069 private Map.Entry<K,V> doRemoveLastEntry() {
1070 for (;;) {
1071 Node<K,V> b = findPredecessorOfLast();
1072 Node<K,V> n = b.next;
1073 if (n == null) {
1074 if (b.isBaseHeader()) // empty
1075 return null;
1076 else
1077 continue; // all b's successors are deleted; retry
1078 }
1079 for (;;) {
1080 Node<K,V> f = n.next;
1081 if (n != b.next) // inconsistent read
1082 break;
1083 Object v = n.value;
1084 if (v == null) { // n is deleted
1085 n.helpDelete(b, f);
1086 break;
1087 }
1088 if (b.value == null || v == n) // b is deleted
1089 break;
1090 if (f != null) {
1091 b = n;
1092 n = f;
1093 continue;
1094 }
1095 if (!n.casValue(v, null))
1096 break;
1097 K key = n.key;
1098 if (!n.appendMarker(f) || !b.casNext(n, f))
1099 findNode(key); // retry via findNode
1100 else { // clean index
1101 findPredecessor(key, comparator);
1102 if (head.right == null)
1103 tryReduceLevel();
1104 }
1105 @SuppressWarnings("unchecked") V vv = (V)v;
1106 return new AbstractMap.SimpleImmutableEntry<K,V>(key, vv);
1107 }
1108 }
1109 }
1110
1111 /* ---------------- Finding and removing last element -------------- */
1112
1113 /**
1114 * Specialized version of find to get last valid node.
1115 * @return last node or null if empty
1116 */
1117 final Node<K,V> findLast() {
1118 /*
1119 * findPredecessor can't be used to traverse index level
1120 * because this doesn't use comparisons. So traversals of
1121 * both levels are folded together.
1122 */
1123 Index<K,V> q = head;
1124 for (;;) {
1125 Index<K,V> d, r;
1126 if ((r = q.right) != null) {
1127 if (r.indexesDeletedNode()) {
1128 q.unlink(r);
1129 q = head; // restart
1130 }
1131 else
1132 q = r;
1133 } else if ((d = q.down) != null) {
1134 q = d;
1135 } else {
1136 for (Node<K,V> b = q.node, n = b.next;;) {
1137 if (n == null)
1138 return b.isBaseHeader() ? null : b;
1139 Node<K,V> f = n.next; // inconsistent read
1140 if (n != b.next)
1141 break;
1142 Object v = n.value;
1143 if (v == null) { // n is deleted
1144 n.helpDelete(b, f);
1145 break;
1146 }
1147 if (b.value == null || v == n) // b is deleted
1148 break;
1149 b = n;
1150 n = f;
1151 }
1152 q = head; // restart
1153 }
1154 }
1155 }
1156
1157 /**
1158 * Specialized variant of findPredecessor to get predecessor of last
1159 * valid node. Needed when removing the last entry. It is possible
1160 * that all successors of returned node will have been deleted upon
1161 * return, in which case this method can be retried.
1162 * @return likely predecessor of last node
1163 */
1164 private Node<K,V> findPredecessorOfLast() {
1165 for (;;) {
1166 for (Index<K,V> q = head;;) {
1167 Index<K,V> d, r;
1168 if ((r = q.right) != null) {
1169 if (r.indexesDeletedNode()) {
1170 q.unlink(r);
1171 break; // must restart
1172 }
1173 // proceed as far across as possible without overshooting
1174 if (r.node.next != null) {
1175 q = r;
1176 continue;
1177 }
1178 }
1179 if ((d = q.down) != null)
1180 q = d;
1181 else
1182 return q.node;
1183 }
1184 }
1185 }
1186
1187 /* ---------------- Relational operations -------------- */
1188
1189 // Control values OR'ed as arguments to findNear
1190
1191 private static final int EQ = 1;
1192 private static final int LT = 2;
1193 private static final int GT = 0; // Actually checked as !LT
1194
1195 /**
1196 * Utility for ceiling, floor, lower, higher methods.
1197 * @param key the key
1198 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1199 * @return nearest node fitting relation, or null if no such
1200 */
1201 final Node<K,V> findNear(K key, int rel, Comparator<? super K> cmp) {
1202 if (key == null)
1203 throw new NullPointerException();
1204 for (;;) {
1205 for (Node<K,V> b = findPredecessor(key, cmp), n = b.next;;) {
1206 Object v;
1207 if (n == null)
1208 return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b;
1209 Node<K,V> f = n.next;
1210 if (n != b.next) // inconsistent read
1211 break;
1212 if ((v = n.value) == null) { // n is deleted
1213 n.helpDelete(b, f);
1214 break;
1215 }
1216 if (b.value == null || v == n) // b is deleted
1217 break;
1218 int c = cpr(cmp, key, n.key);
1219 if ((c == 0 && (rel & EQ) != 0) ||
1220 (c < 0 && (rel & LT) == 0))
1221 return n;
1222 if ( c <= 0 && (rel & LT) != 0)
1223 return b.isBaseHeader() ? null : b;
1224 b = n;
1225 n = f;
1226 }
1227 }
1228 }
1229
1230 /**
1231 * Returns SimpleImmutableEntry for results of findNear.
1232 * @param key the key
1233 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1234 * @return Entry fitting relation, or null if no such
1235 */
1236 final AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
1237 Comparator<? super K> cmp = comparator;
1238 for (;;) {
1239 Node<K,V> n = findNear(key, rel, cmp);
1240 if (n == null)
1241 return null;
1242 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1243 if (e != null)
1244 return e;
1245 }
1246 }
1247
1248 /* ---------------- Constructors -------------- */
1249
1250 /**
1251 * Constructs a new, empty map, sorted according to the
1252 * {@linkplain Comparable natural ordering} of the keys.
1253 */
1254 public ConcurrentSkipListMap() {
1255 this.comparator = null;
1256 initialize();
1257 }
1258
1259 /**
1260 * Constructs a new, empty map, sorted according to the specified
1261 * comparator.
1262 *
1263 * @param comparator the comparator that will be used to order this map.
1264 * If {@code null}, the {@linkplain Comparable natural
1265 * ordering} of the keys will be used.
1266 */
1267 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1268 this.comparator = comparator;
1269 initialize();
1270 }
1271
1272 /**
1273 * Constructs a new map containing the same mappings as the given map,
1274 * sorted according to the {@linkplain Comparable natural ordering} of
1275 * the keys.
1276 *
1277 * @param m the map whose mappings are to be placed in this map
1278 * @throws ClassCastException if the keys in {@code m} are not
1279 * {@link Comparable}, or are not mutually comparable
1280 * @throws NullPointerException if the specified map or any of its keys
1281 * or values are null
1282 */
1283 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1284 this.comparator = null;
1285 initialize();
1286 putAll(m);
1287 }
1288
1289 /**
1290 * Constructs a new map containing the same mappings and using the
1291 * same ordering as the specified sorted map.
1292 *
1293 * @param m the sorted map whose mappings are to be placed in this
1294 * map, and whose comparator is to be used to sort this map
1295 * @throws NullPointerException if the specified sorted map or any of
1296 * its keys or values are null
1297 */
1298 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1299 this.comparator = m.comparator();
1300 initialize();
1301 buildFromSorted(m);
1302 }
1303
1304 /**
1305 * Returns a shallow copy of this {@code ConcurrentSkipListMap}
1306 * instance. (The keys and values themselves are not cloned.)
1307 *
1308 * @return a shallow copy of this map
1309 */
1310 public ConcurrentSkipListMap<K,V> clone() {
1311 try {
1312 @SuppressWarnings("unchecked")
1313 ConcurrentSkipListMap<K,V> clone =
1314 (ConcurrentSkipListMap<K,V>) super.clone();
1315 clone.initialize();
1316 clone.buildFromSorted(this);
1317 return clone;
1318 } catch (CloneNotSupportedException e) {
1319 throw new InternalError();
1320 }
1321 }
1322
1323 /**
1324 * Streamlined bulk insertion to initialize from elements of
1325 * given sorted map. Call only from constructor or clone
1326 * method.
1327 */
1328 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1329 if (map == null)
1330 throw new NullPointerException();
1331
1332 HeadIndex<K,V> h = head;
1333 Node<K,V> basepred = h.node;
1334
1335 // Track the current rightmost node at each level. Uses an
1336 // ArrayList to avoid committing to initial or maximum level.
1337 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1338
1339 // initialize
1340 for (int i = 0; i <= h.level; ++i)
1341 preds.add(null);
1342 Index<K,V> q = h;
1343 for (int i = h.level; i > 0; --i) {
1344 preds.set(i, q);
1345 q = q.down;
1346 }
1347
1348 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1349 map.entrySet().iterator();
1350 while (it.hasNext()) {
1351 Map.Entry<? extends K, ? extends V> e = it.next();
1352 int rnd = ThreadLocalRandom.current().nextInt();
1353 int j = 0;
1354 if ((rnd & 0x80000001) == 0) {
1355 do {
1356 ++j;
1357 } while (((rnd >>>= 1) & 1) != 0);
1358 if (j > h.level) j = h.level + 1;
1359 }
1360 K k = e.getKey();
1361 V v = e.getValue();
1362 if (k == null || v == null)
1363 throw new NullPointerException();
1364 Node<K,V> z = new Node<K,V>(k, v, null);
1365 basepred.next = z;
1366 basepred = z;
1367 if (j > 0) {
1368 Index<K,V> idx = null;
1369 for (int i = 1; i <= j; ++i) {
1370 idx = new Index<K,V>(z, idx, null);
1371 if (i > h.level)
1372 h = new HeadIndex<K,V>(h.node, h, idx, i);
1373
1374 if (i < preds.size()) {
1375 preds.get(i).right = idx;
1376 preds.set(i, idx);
1377 } else
1378 preds.add(idx);
1379 }
1380 }
1381 }
1382 head = h;
1383 }
1384
1385 /* ---------------- Serialization -------------- */
1386
1387 /**
1388 * Saves this map to a stream (that is, serializes it).
1389 *
1390 * @serialData The key (Object) and value (Object) for each
1391 * key-value mapping represented by the map, followed by
1392 * {@code null}. The key-value mappings are emitted in key-order
1393 * (as determined by the Comparator, or by the keys' natural
1394 * ordering if no Comparator).
1395 */
1396 private void writeObject(java.io.ObjectOutputStream s)
1397 throws java.io.IOException {
1398 // Write out the Comparator and any hidden stuff
1399 s.defaultWriteObject();
1400
1401 // Write out keys and values (alternating)
1402 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1403 V v = n.getValidValue();
1404 if (v != null) {
1405 s.writeObject(n.key);
1406 s.writeObject(v);
1407 }
1408 }
1409 s.writeObject(null);
1410 }
1411
1412 /**
1413 * Reconstitutes this map from a stream (that is, deserializes it).
1414 */
1415 @SuppressWarnings("unchecked")
1416 private void readObject(final java.io.ObjectInputStream s)
1417 throws java.io.IOException, ClassNotFoundException {
1418 // Read in the Comparator and any hidden stuff
1419 s.defaultReadObject();
1420 // Reset transients
1421 initialize();
1422
1423 /*
1424 * This is nearly identical to buildFromSorted, but is
1425 * distinct because readObject calls can't be nicely adapted
1426 * as the kind of iterator needed by buildFromSorted. (They
1427 * can be, but doing so requires type cheats and/or creation
1428 * of adaptor classes.) It is simpler to just adapt the code.
1429 */
1430
1431 HeadIndex<K,V> h = head;
1432 Node<K,V> basepred = h.node;
1433 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1434 for (int i = 0; i <= h.level; ++i)
1435 preds.add(null);
1436 Index<K,V> q = h;
1437 for (int i = h.level; i > 0; --i) {
1438 preds.set(i, q);
1439 q = q.down;
1440 }
1441
1442 for (;;) {
1443 Object k = s.readObject();
1444 if (k == null)
1445 break;
1446 Object v = s.readObject();
1447 if (v == null)
1448 throw new NullPointerException();
1449 K key = (K) k;
1450 V val = (V) v;
1451 int rnd = ThreadLocalRandom.current().nextInt();
1452 int j = 0;
1453 if ((rnd & 0x80000001) == 0) {
1454 do {
1455 ++j;
1456 } while (((rnd >>>= 1) & 1) != 0);
1457 if (j > h.level) j = h.level + 1;
1458 }
1459 Node<K,V> z = new Node<K,V>(key, val, null);
1460 basepred.next = z;
1461 basepred = z;
1462 if (j > 0) {
1463 Index<K,V> idx = null;
1464 for (int i = 1; i <= j; ++i) {
1465 idx = new Index<K,V>(z, idx, null);
1466 if (i > h.level)
1467 h = new HeadIndex<K,V>(h.node, h, idx, i);
1468
1469 if (i < preds.size()) {
1470 preds.get(i).right = idx;
1471 preds.set(i, idx);
1472 } else
1473 preds.add(idx);
1474 }
1475 }
1476 }
1477 head = h;
1478 }
1479
1480 /* ------ Map API methods ------ */
1481
1482 /**
1483 * Returns {@code true} if this map contains a mapping for the specified
1484 * key.
1485 *
1486 * @param key key whose presence in this map is to be tested
1487 * @return {@code true} if this map contains a mapping for the specified key
1488 * @throws ClassCastException if the specified key cannot be compared
1489 * with the keys currently in the map
1490 * @throws NullPointerException if the specified key is null
1491 */
1492 public boolean containsKey(Object key) {
1493 return doGet(key) != null;
1494 }
1495
1496 /**
1497 * Returns the value to which the specified key is mapped,
1498 * or {@code null} if this map contains no mapping for the key.
1499 *
1500 * <p>More formally, if this map contains a mapping from a key
1501 * {@code k} to a value {@code v} such that {@code key} compares
1502 * equal to {@code k} according to the map's ordering, then this
1503 * method returns {@code v}; otherwise it returns {@code null}.
1504 * (There can be at most one such mapping.)
1505 *
1506 * @throws ClassCastException if the specified key cannot be compared
1507 * with the keys currently in the map
1508 * @throws NullPointerException if the specified key is null
1509 */
1510 public V get(Object key) {
1511 return doGet(key);
1512 }
1513
1514 /**
1515 * Returns the value to which the specified key is mapped,
1516 * or the given defaultValue if this map contains no mapping for the key.
1517 *
1518 * @param key the key
1519 * @param defaultValue the value to return if this map contains
1520 * no mapping for the given key
1521 * @return the mapping for the key, if present; else the defaultValue
1522 * @throws NullPointerException if the specified key is null
1523 * @since 1.8
1524 */
1525 public V getOrDefault(Object key, V defaultValue) {
1526 V v;
1527 return (v = doGet(key)) == null ? defaultValue : v;
1528 }
1529
1530 /**
1531 * Associates the specified value with the specified key in this map.
1532 * If the map previously contained a mapping for the key, the old
1533 * value is replaced.
1534 *
1535 * @param key key with which the specified value is to be associated
1536 * @param value value to be associated with the specified key
1537 * @return the previous value associated with the specified key, or
1538 * {@code null} if there was no mapping for the key
1539 * @throws ClassCastException if the specified key cannot be compared
1540 * with the keys currently in the map
1541 * @throws NullPointerException if the specified key or value is null
1542 */
1543 public V put(K key, V value) {
1544 if (value == null)
1545 throw new NullPointerException();
1546 return doPut(key, value, false);
1547 }
1548
1549 /**
1550 * Removes the mapping for the specified key from this map if present.
1551 *
1552 * @param key key for which mapping should be removed
1553 * @return the previous value associated with the specified key, or
1554 * {@code null} if there was no mapping for the key
1555 * @throws ClassCastException if the specified key cannot be compared
1556 * with the keys currently in the map
1557 * @throws NullPointerException if the specified key is null
1558 */
1559 public V remove(Object key) {
1560 return doRemove(key, null);
1561 }
1562
1563 /**
1564 * Returns {@code true} if this map maps one or more keys to the
1565 * specified value. This operation requires time linear in the
1566 * map size. Additionally, it is possible for the map to change
1567 * during execution of this method, in which case the returned
1568 * result may be inaccurate.
1569 *
1570 * @param value value whose presence in this map is to be tested
1571 * @return {@code true} if a mapping to {@code value} exists;
1572 * {@code false} otherwise
1573 * @throws NullPointerException if the specified value is null
1574 */
1575 public boolean containsValue(Object value) {
1576 if (value == null)
1577 throw new NullPointerException();
1578 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1579 V v = n.getValidValue();
1580 if (v != null && value.equals(v))
1581 return true;
1582 }
1583 return false;
1584 }
1585
1586 /**
1587 * Returns the number of key-value mappings in this map. If this map
1588 * contains more than {@code Integer.MAX_VALUE} elements, it
1589 * returns {@code Integer.MAX_VALUE}.
1590 *
1591 * <p>Beware that, unlike in most collections, this method is
1592 * <em>NOT</em> a constant-time operation. Because of the
1593 * asynchronous nature of these maps, determining the current
1594 * number of elements requires traversing them all to count them.
1595 * Additionally, it is possible for the size to change during
1596 * execution of this method, in which case the returned result
1597 * will be inaccurate. Thus, this method is typically not very
1598 * useful in concurrent applications.
1599 *
1600 * @return the number of elements in this map
1601 */
1602 public int size() {
1603 long count = 0;
1604 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1605 if (n.getValidValue() != null)
1606 ++count;
1607 }
1608 return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count;
1609 }
1610
1611 /**
1612 * Returns {@code true} if this map contains no key-value mappings.
1613 * @return {@code true} if this map contains no key-value mappings
1614 */
1615 public boolean isEmpty() {
1616 return findFirst() == null;
1617 }
1618
1619 /**
1620 * Removes all of the mappings from this map.
1621 */
1622 public void clear() {
1623 initialize();
1624 }
1625
1626 /**
1627 * If the specified key is not already associated with a value,
1628 * attempts to compute its value using the given mapping function
1629 * and enters it into this map unless {@code null}. The function
1630 * is <em>NOT</em> guaranteed to be applied once atomically only
1631 * if the value is not present.
1632 *
1633 * @param key key with which the specified value is to be associated
1634 * @param mappingFunction the function to compute a value
1635 * @return the current (existing or computed) value associated with
1636 * the specified key, or null if the computed value is null
1637 * @throws NullPointerException if the specified key is null
1638 * or the mappingFunction is null
1639 * @since 1.8
1640 */
1641 public V computeIfAbsent(K key,
1642 Function<? super K, ? extends V> mappingFunction) {
1643 if (key == null || mappingFunction == null)
1644 throw new NullPointerException();
1645 V v, p, r;
1646 if ((v = doGet(key)) == null &&
1647 (r = mappingFunction.apply(key)) != null)
1648 v = (p = doPut(key, r, true)) == null ? r : p;
1649 return v;
1650 }
1651
1652 /**
1653 * If the value for the specified key is present, attempts to
1654 * compute a new mapping given the key and its current mapped
1655 * value. The function is <em>NOT</em> guaranteed to be applied
1656 * once atomically.
1657 *
1658 * @param key key with which a value may be associated
1659 * @param remappingFunction the function to compute a value
1660 * @return the new value associated with the specified key, or null if none
1661 * @throws NullPointerException if the specified key is null
1662 * or the remappingFunction is null
1663 * @since 1.8
1664 */
1665 public V computeIfPresent(K key,
1666 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1667 if (key == null || remappingFunction == null)
1668 throw new NullPointerException();
1669 Node<K,V> n; Object v;
1670 while ((n = findNode(key)) != null) {
1671 if ((v = n.value) != null) {
1672 @SuppressWarnings("unchecked") V vv = (V) v;
1673 V r = remappingFunction.apply(key, vv);
1674 if (r != null) {
1675 if (n.casValue(vv, r))
1676 return r;
1677 }
1678 else if (doRemove(key, vv) != null)
1679 break;
1680 }
1681 }
1682 return null;
1683 }
1684
1685 /**
1686 * Attempts to compute a mapping for the specified key and its
1687 * current mapped value (or {@code null} if there is no current
1688 * mapping). The function is <em>NOT</em> guaranteed to be applied
1689 * once atomically.
1690 *
1691 * @param key key with which the specified value is to be associated
1692 * @param remappingFunction the function to compute a value
1693 * @return the new value associated with the specified key, or null if none
1694 * @throws NullPointerException if the specified key is null
1695 * or the remappingFunction is null
1696 * @since 1.8
1697 */
1698 public V compute(K key,
1699 BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1700 if (key == null || remappingFunction == null)
1701 throw new NullPointerException();
1702 for (;;) {
1703 Node<K,V> n; Object v; V r;
1704 if ((n = findNode(key)) == null) {
1705 if ((r = remappingFunction.apply(key, null)) == null)
1706 break;
1707 if (doPut(key, r, true) == null)
1708 return r;
1709 }
1710 else if ((v = n.value) != null) {
1711 @SuppressWarnings("unchecked") V vv = (V) v;
1712 if ((r = remappingFunction.apply(key, vv)) != null) {
1713 if (n.casValue(vv, r))
1714 return r;
1715 }
1716 else if (doRemove(key, vv) != null)
1717 break;
1718 }
1719 }
1720 return null;
1721 }
1722
1723 /**
1724 * If the specified key is not already associated with a value,
1725 * associates it with the given value. Otherwise, replaces the
1726 * value with the results of the given remapping function, or
1727 * removes if {@code null}. The function is <em>NOT</em>
1728 * guaranteed to be applied once atomically.
1729 *
1730 * @param key key with which the specified value is to be associated
1731 * @param value the value to use if absent
1732 * @param remappingFunction the function to recompute a value if present
1733 * @return the new value associated with the specified key, or null if none
1734 * @throws NullPointerException if the specified key or value is null
1735 * or the remappingFunction is null
1736 * @since 1.8
1737 */
1738 public V merge(K key, V value,
1739 BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
1740 if (key == null || value == null || remappingFunction == null)
1741 throw new NullPointerException();
1742 for (;;) {
1743 Node<K,V> n; Object v; V r;
1744 if ((n = findNode(key)) == null) {
1745 if (doPut(key, value, true) == null)
1746 return value;
1747 }
1748 else if ((v = n.value) != null) {
1749 @SuppressWarnings("unchecked") V vv = (V) v;
1750 if ((r = remappingFunction.apply(vv, value)) != null) {
1751 if (n.casValue(vv, r))
1752 return r;
1753 }
1754 else if (doRemove(key, vv) != null)
1755 return null;
1756 }
1757 }
1758 }
1759
1760 /* ---------------- View methods -------------- */
1761
1762 /*
1763 * Note: Lazy initialization works for views because view classes
1764 * are stateless/immutable so it doesn't matter wrt correctness if
1765 * more than one is created (which will only rarely happen). Even
1766 * so, the following idiom conservatively ensures that the method
1767 * returns the one it created if it does so, not one created by
1768 * another racing thread.
1769 */
1770
1771 /**
1772 * Returns a {@link NavigableSet} view of the keys contained in this map.
1773 * The set's iterator returns the keys in ascending order.
1774 * The set is backed by the map, so changes to the map are
1775 * reflected in the set, and vice-versa. The set supports element
1776 * removal, which removes the corresponding mapping from the map,
1777 * via the {@code Iterator.remove}, {@code Set.remove},
1778 * {@code removeAll}, {@code retainAll}, and {@code clear}
1779 * operations. It does not support the {@code add} or {@code addAll}
1780 * operations.
1781 *
1782 * <p>The view's {@code iterator} is a "weakly consistent" iterator that
1783 * will never throw {@link java.util.ConcurrentModificationException
1784 * ConcurrentModificationException}, and guarantees to traverse elements
1785 * as they existed upon construction of the iterator, and may (but is not
1786 * guaranteed to) reflect any modifications subsequent to construction.
1787 *
1788 * <p>This method is equivalent to method {@code navigableKeySet}.
1789 *
1790 * @return a navigable set view of the keys in this map
1791 */
1792 public NavigableSet<K> keySet() {
1793 KeySet<K> ks = keySet;
1794 return (ks != null) ? ks : (keySet = new KeySet<K>(this));
1795 }
1796
1797 public NavigableSet<K> navigableKeySet() {
1798 KeySet<K> ks = keySet;
1799 return (ks != null) ? ks : (keySet = new KeySet<K>(this));
1800 }
1801
1802 /**
1803 * Returns a {@link Collection} view of the values contained in this map.
1804 * The collection's iterator returns the values in ascending order
1805 * of the corresponding keys.
1806 * The collection is backed by the map, so changes to the map are
1807 * reflected in the collection, and vice-versa. The collection
1808 * supports element removal, which removes the corresponding
1809 * mapping from the map, via the {@code Iterator.remove},
1810 * {@code Collection.remove}, {@code removeAll},
1811 * {@code retainAll} and {@code clear} operations. It does not
1812 * support the {@code add} or {@code addAll} operations.
1813 *
1814 * <p>The view's {@code iterator} is a "weakly consistent" iterator that
1815 * will never throw {@link java.util.ConcurrentModificationException
1816 * ConcurrentModificationException}, and guarantees to traverse elements
1817 * as they existed upon construction of the iterator, and may (but is not
1818 * guaranteed to) reflect any modifications subsequent to construction.
1819 */
1820 public Collection<V> values() {
1821 Values<V> vs = values;
1822 return (vs != null) ? vs : (values = new Values<V>(this));
1823 }
1824
1825 /**
1826 * Returns a {@link Set} view of the mappings contained in this map.
1827 * The set's iterator returns the entries in ascending key order.
1828 * The set is backed by the map, so changes to the map are
1829 * reflected in the set, and vice-versa. The set supports element
1830 * removal, which removes the corresponding mapping from the map,
1831 * via the {@code Iterator.remove}, {@code Set.remove},
1832 * {@code removeAll}, {@code retainAll} and {@code clear}
1833 * operations. It does not support the {@code add} or
1834 * {@code addAll} operations.
1835 *
1836 * <p>The view's {@code iterator} is a "weakly consistent" iterator that
1837 * will never throw {@link java.util.ConcurrentModificationException
1838 * ConcurrentModificationException}, and guarantees to traverse elements
1839 * as they existed upon construction of the iterator, and may (but is not
1840 * guaranteed to) reflect any modifications subsequent to construction.
1841 *
1842 * <p>The {@code Map.Entry} elements returned by
1843 * {@code iterator.next()} do <em>not</em> support the
1844 * {@code setValue} operation.
1845 *
1846 * @return a set view of the mappings contained in this map,
1847 * sorted in ascending key order
1848 */
1849 public Set<Map.Entry<K,V>> entrySet() {
1850 EntrySet<K,V> es = entrySet;
1851 return (es != null) ? es : (entrySet = new EntrySet<K,V>(this));
1852 }
1853
1854 public ConcurrentNavigableMap<K,V> descendingMap() {
1855 ConcurrentNavigableMap<K,V> dm = descendingMap;
1856 return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
1857 (this, null, false, null, false, true));
1858 }
1859
1860 public NavigableSet<K> descendingKeySet() {
1861 return descendingMap().navigableKeySet();
1862 }
1863
1864 /* ---------------- AbstractMap Overrides -------------- */
1865
1866 /**
1867 * Compares the specified object with this map for equality.
1868 * Returns {@code true} if the given object is also a map and the
1869 * two maps represent the same mappings. More formally, two maps
1870 * {@code m1} and {@code m2} represent the same mappings if
1871 * {@code m1.entrySet().equals(m2.entrySet())}. This
1872 * operation may return misleading results if either map is
1873 * concurrently modified during execution of this method.
1874 *
1875 * @param o object to be compared for equality with this map
1876 * @return {@code true} if the specified object is equal to this map
1877 */
1878 public boolean equals(Object o) {
1879 if (o == this)
1880 return true;
1881 if (!(o instanceof Map))
1882 return false;
1883 Map<?,?> m = (Map<?,?>) o;
1884 try {
1885 for (Map.Entry<K,V> e : this.entrySet())
1886 if (! e.getValue().equals(m.get(e.getKey())))
1887 return false;
1888 for (Map.Entry<?,?> e : m.entrySet()) {
1889 Object k = e.getKey();
1890 Object v = e.getValue();
1891 if (k == null || v == null || !v.equals(get(k)))
1892 return false;
1893 }
1894 return true;
1895 } catch (ClassCastException unused) {
1896 return false;
1897 } catch (NullPointerException unused) {
1898 return false;
1899 }
1900 }
1901
1902 /* ------ ConcurrentMap API methods ------ */
1903
1904 /**
1905 * {@inheritDoc}
1906 *
1907 * @return the previous value associated with the specified key,
1908 * or {@code null} if there was no mapping for the key
1909 * @throws ClassCastException if the specified key cannot be compared
1910 * with the keys currently in the map
1911 * @throws NullPointerException if the specified key or value is null
1912 */
1913 public V putIfAbsent(K key, V value) {
1914 if (value == null)
1915 throw new NullPointerException();
1916 return doPut(key, value, true);
1917 }
1918
1919 /**
1920 * {@inheritDoc}
1921 *
1922 * @throws ClassCastException if the specified key cannot be compared
1923 * with the keys currently in the map
1924 * @throws NullPointerException if the specified key is null
1925 */
1926 public boolean remove(Object key, Object value) {
1927 if (key == null)
1928 throw new NullPointerException();
1929 return value != null && doRemove(key, value) != null;
1930 }
1931
1932 /**
1933 * {@inheritDoc}
1934 *
1935 * @throws ClassCastException if the specified key cannot be compared
1936 * with the keys currently in the map
1937 * @throws NullPointerException if any of the arguments are null
1938 */
1939 public boolean replace(K key, V oldValue, V newValue) {
1940 if (key == null || oldValue == null || newValue == null)
1941 throw new NullPointerException();
1942 for (;;) {
1943 Node<K,V> n; Object v;
1944 if ((n = findNode(key)) == null)
1945 return false;
1946 if ((v = n.value) != null) {
1947 if (!oldValue.equals(v))
1948 return false;
1949 if (n.casValue(v, newValue))
1950 return true;
1951 }
1952 }
1953 }
1954
1955 /**
1956 * {@inheritDoc}
1957 *
1958 * @return the previous value associated with the specified key,
1959 * or {@code null} if there was no mapping for the key
1960 * @throws ClassCastException if the specified key cannot be compared
1961 * with the keys currently in the map
1962 * @throws NullPointerException if the specified key or value is null
1963 */
1964 public V replace(K key, V value) {
1965 if (key == null || value == null)
1966 throw new NullPointerException();
1967 for (;;) {
1968 Node<K,V> n; Object v;
1969 if ((n = findNode(key)) == null)
1970 return null;
1971 if ((v = n.value) != null && n.casValue(v, value)) {
1972 @SuppressWarnings("unchecked") V vv = (V)v;
1973 return vv;
1974 }
1975 }
1976 }
1977
1978 /* ------ SortedMap API methods ------ */
1979
1980 public Comparator<? super K> comparator() {
1981 return comparator;
1982 }
1983
1984 /**
1985 * @throws NoSuchElementException {@inheritDoc}
1986 */
1987 public K firstKey() {
1988 Node<K,V> n = findFirst();
1989 if (n == null)
1990 throw new NoSuchElementException();
1991 return n.key;
1992 }
1993
1994 /**
1995 * @throws NoSuchElementException {@inheritDoc}
1996 */
1997 public K lastKey() {
1998 Node<K,V> n = findLast();
1999 if (n == null)
2000 throw new NoSuchElementException();
2001 return n.key;
2002 }
2003
2004 /**
2005 * @throws ClassCastException {@inheritDoc}
2006 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2007 * @throws IllegalArgumentException {@inheritDoc}
2008 */
2009 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
2010 boolean fromInclusive,
2011 K toKey,
2012 boolean toInclusive) {
2013 if (fromKey == null || toKey == null)
2014 throw new NullPointerException();
2015 return new SubMap<K,V>
2016 (this, fromKey, fromInclusive, toKey, toInclusive, false);
2017 }
2018
2019 /**
2020 * @throws ClassCastException {@inheritDoc}
2021 * @throws NullPointerException if {@code toKey} is null
2022 * @throws IllegalArgumentException {@inheritDoc}
2023 */
2024 public ConcurrentNavigableMap<K,V> headMap(K toKey,
2025 boolean inclusive) {
2026 if (toKey == null)
2027 throw new NullPointerException();
2028 return new SubMap<K,V>
2029 (this, null, false, toKey, inclusive, false);
2030 }
2031
2032 /**
2033 * @throws ClassCastException {@inheritDoc}
2034 * @throws NullPointerException if {@code fromKey} is null
2035 * @throws IllegalArgumentException {@inheritDoc}
2036 */
2037 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2038 boolean inclusive) {
2039 if (fromKey == null)
2040 throw new NullPointerException();
2041 return new SubMap<K,V>
2042 (this, fromKey, inclusive, null, false, false);
2043 }
2044
2045 /**
2046 * @throws ClassCastException {@inheritDoc}
2047 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2048 * @throws IllegalArgumentException {@inheritDoc}
2049 */
2050 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2051 return subMap(fromKey, true, toKey, false);
2052 }
2053
2054 /**
2055 * @throws ClassCastException {@inheritDoc}
2056 * @throws NullPointerException if {@code toKey} is null
2057 * @throws IllegalArgumentException {@inheritDoc}
2058 */
2059 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2060 return headMap(toKey, false);
2061 }
2062
2063 /**
2064 * @throws ClassCastException {@inheritDoc}
2065 * @throws NullPointerException if {@code fromKey} is null
2066 * @throws IllegalArgumentException {@inheritDoc}
2067 */
2068 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2069 return tailMap(fromKey, true);
2070 }
2071
2072 /* ---------------- Relational operations -------------- */
2073
2074 /**
2075 * Returns a key-value mapping associated with the greatest key
2076 * strictly less than the given key, or {@code null} if there is
2077 * no such key. The returned entry does <em>not</em> support the
2078 * {@code Entry.setValue} method.
2079 *
2080 * @throws ClassCastException {@inheritDoc}
2081 * @throws NullPointerException if the specified key is null
2082 */
2083 public Map.Entry<K,V> lowerEntry(K key) {
2084 return getNear(key, LT);
2085 }
2086
2087 /**
2088 * @throws ClassCastException {@inheritDoc}
2089 * @throws NullPointerException if the specified key is null
2090 */
2091 public K lowerKey(K key) {
2092 Node<K,V> n = findNear(key, LT, comparator);
2093 return (n == null) ? null : n.key;
2094 }
2095
2096 /**
2097 * Returns a key-value mapping associated with the greatest key
2098 * less than or equal to the given key, or {@code null} if there
2099 * is no such key. The returned entry does <em>not</em> support
2100 * the {@code Entry.setValue} method.
2101 *
2102 * @param key the key
2103 * @throws ClassCastException {@inheritDoc}
2104 * @throws NullPointerException if the specified key is null
2105 */
2106 public Map.Entry<K,V> floorEntry(K key) {
2107 return getNear(key, LT|EQ);
2108 }
2109
2110 /**
2111 * @param key the key
2112 * @throws ClassCastException {@inheritDoc}
2113 * @throws NullPointerException if the specified key is null
2114 */
2115 public K floorKey(K key) {
2116 Node<K,V> n = findNear(key, LT|EQ, comparator);
2117 return (n == null) ? null : n.key;
2118 }
2119
2120 /**
2121 * Returns a key-value mapping associated with the least key
2122 * greater than or equal to the given key, or {@code null} if
2123 * there is no such entry. The returned entry does <em>not</em>
2124 * support the {@code Entry.setValue} method.
2125 *
2126 * @throws ClassCastException {@inheritDoc}
2127 * @throws NullPointerException if the specified key is null
2128 */
2129 public Map.Entry<K,V> ceilingEntry(K key) {
2130 return getNear(key, GT|EQ);
2131 }
2132
2133 /**
2134 * @throws ClassCastException {@inheritDoc}
2135 * @throws NullPointerException if the specified key is null
2136 */
2137 public K ceilingKey(K key) {
2138 Node<K,V> n = findNear(key, GT|EQ, comparator);
2139 return (n == null) ? null : n.key;
2140 }
2141
2142 /**
2143 * Returns a key-value mapping associated with the least key
2144 * strictly greater than the given key, or {@code null} if there
2145 * is no such key. The returned entry does <em>not</em> support
2146 * the {@code Entry.setValue} method.
2147 *
2148 * @param key the key
2149 * @throws ClassCastException {@inheritDoc}
2150 * @throws NullPointerException if the specified key is null
2151 */
2152 public Map.Entry<K,V> higherEntry(K key) {
2153 return getNear(key, GT);
2154 }
2155
2156 /**
2157 * @param key the key
2158 * @throws ClassCastException {@inheritDoc}
2159 * @throws NullPointerException if the specified key is null
2160 */
2161 public K higherKey(K key) {
2162 Node<K,V> n = findNear(key, GT, comparator);
2163 return (n == null) ? null : n.key;
2164 }
2165
2166 /**
2167 * Returns a key-value mapping associated with the least
2168 * key in this map, or {@code null} if the map is empty.
2169 * The returned entry does <em>not</em> support
2170 * the {@code Entry.setValue} method.
2171 */
2172 public Map.Entry<K,V> firstEntry() {
2173 for (;;) {
2174 Node<K,V> n = findFirst();
2175 if (n == null)
2176 return null;
2177 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2178 if (e != null)
2179 return e;
2180 }
2181 }
2182
2183 /**
2184 * Returns a key-value mapping associated with the greatest
2185 * key in this map, or {@code null} if the map is empty.
2186 * The returned entry does <em>not</em> support
2187 * the {@code Entry.setValue} method.
2188 */
2189 public Map.Entry<K,V> lastEntry() {
2190 for (;;) {
2191 Node<K,V> n = findLast();
2192 if (n == null)
2193 return null;
2194 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2195 if (e != null)
2196 return e;
2197 }
2198 }
2199
2200 /**
2201 * Removes and returns a key-value mapping associated with
2202 * the least key in this map, or {@code null} if the map is empty.
2203 * The returned entry does <em>not</em> support
2204 * the {@code Entry.setValue} method.
2205 */
2206 public Map.Entry<K,V> pollFirstEntry() {
2207 return doRemoveFirstEntry();
2208 }
2209
2210 /**
2211 * Removes and returns a key-value mapping associated with
2212 * the greatest key in this map, or {@code null} if the map is empty.
2213 * The returned entry does <em>not</em> support
2214 * the {@code Entry.setValue} method.
2215 */
2216 public Map.Entry<K,V> pollLastEntry() {
2217 return doRemoveLastEntry();
2218 }
2219
2220
2221 /* ---------------- Iterators -------------- */
2222
2223 /**
2224 * Base of iterator classes:
2225 */
2226 abstract class Iter<T> implements Iterator<T> {
2227 /** the last node returned by next() */
2228 Node<K,V> lastReturned;
2229 /** the next node to return from next(); */
2230 Node<K,V> next;
2231 /** Cache of next value field to maintain weak consistency */
2232 V nextValue;
2233
2234 /** Initializes ascending iterator for entire range. */
2235 Iter() {
2236 while ((next = findFirst()) != null) {
2237 Object x = next.value;
2238 if (x != null && x != next) {
2239 @SuppressWarnings("unchecked") V vv = (V)x;
2240 nextValue = vv;
2241 break;
2242 }
2243 }
2244 }
2245
2246 public final boolean hasNext() {
2247 return next != null;
2248 }
2249
2250 /** Advances next to higher entry. */
2251 final void advance() {
2252 if (next == null)
2253 throw new NoSuchElementException();
2254 lastReturned = next;
2255 while ((next = next.next) != null) {
2256 Object x = next.value;
2257 if (x != null && x != next) {
2258 @SuppressWarnings("unchecked") V vv = (V)x;
2259 nextValue = vv;
2260 break;
2261 }
2262 }
2263 }
2264
2265 public void remove() {
2266 Node<K,V> l = lastReturned;
2267 if (l == null)
2268 throw new IllegalStateException();
2269 // It would not be worth all of the overhead to directly
2270 // unlink from here. Using remove is fast enough.
2271 ConcurrentSkipListMap.this.remove(l.key);
2272 lastReturned = null;
2273 }
2274
2275 }
2276
2277 final class ValueIterator extends Iter<V> {
2278 public V next() {
2279 V v = nextValue;
2280 advance();
2281 return v;
2282 }
2283 }
2284
2285 final class KeyIterator extends Iter<K> {
2286 public K next() {
2287 Node<K,V> n = next;
2288 advance();
2289 return n.key;
2290 }
2291 }
2292
2293 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2294 public Map.Entry<K,V> next() {
2295 Node<K,V> n = next;
2296 V v = nextValue;
2297 advance();
2298 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2299 }
2300 }
2301
2302 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2303
2304 Iterator<K> keyIterator() {
2305 return new KeyIterator();
2306 }
2307
2308 Iterator<V> valueIterator() {
2309 return new ValueIterator();
2310 }
2311
2312 Iterator<Map.Entry<K,V>> entryIterator() {
2313 return new EntryIterator();
2314 }
2315
2316 /* ---------------- View Classes -------------- */
2317
2318 /*
2319 * View classes are static, delegating to a ConcurrentNavigableMap
2320 * to allow use by SubMaps, which outweighs the ugliness of
2321 * needing type-tests for Iterator methods.
2322 */
2323
2324 static final <E> List<E> toList(Collection<E> c) {
2325 // Using size() here would be a pessimization.
2326 ArrayList<E> list = new ArrayList<E>();
2327 for (E e : c)
2328 list.add(e);
2329 return list;
2330 }
2331
2332 static final class KeySet<E>
2333 extends AbstractSet<E> implements NavigableSet<E> {
2334 final ConcurrentNavigableMap<E,?> m;
2335 KeySet(ConcurrentNavigableMap<E,?> map) { m = map; }
2336 public int size() { return m.size(); }
2337 public boolean isEmpty() { return m.isEmpty(); }
2338 public boolean contains(Object o) { return m.containsKey(o); }
2339 public boolean remove(Object o) { return m.remove(o) != null; }
2340 public void clear() { m.clear(); }
2341 public E lower(E e) { return m.lowerKey(e); }
2342 public E floor(E e) { return m.floorKey(e); }
2343 public E ceiling(E e) { return m.ceilingKey(e); }
2344 public E higher(E e) { return m.higherKey(e); }
2345 public Comparator<? super E> comparator() { return m.comparator(); }
2346 public E first() { return m.firstKey(); }
2347 public E last() { return m.lastKey(); }
2348 public E pollFirst() {
2349 Map.Entry<E,?> e = m.pollFirstEntry();
2350 return (e == null) ? null : e.getKey();
2351 }
2352 public E pollLast() {
2353 Map.Entry<E,?> e = m.pollLastEntry();
2354 return (e == null) ? null : e.getKey();
2355 }
2356 @SuppressWarnings("unchecked")
2357 public Iterator<E> iterator() {
2358 if (m instanceof ConcurrentSkipListMap)
2359 return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2360 else
2361 return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2362 }
2363 public boolean equals(Object o) {
2364 if (o == this)
2365 return true;
2366 if (!(o instanceof Set))
2367 return false;
2368 Collection<?> c = (Collection<?>) o;
2369 try {
2370 return containsAll(c) && c.containsAll(this);
2371 } catch (ClassCastException unused) {
2372 return false;
2373 } catch (NullPointerException unused) {
2374 return false;
2375 }
2376 }
2377 public Object[] toArray() { return toList(this).toArray(); }
2378 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2379 public Iterator<E> descendingIterator() {
2380 return descendingSet().iterator();
2381 }
2382 public NavigableSet<E> subSet(E fromElement,
2383 boolean fromInclusive,
2384 E toElement,
2385 boolean toInclusive) {
2386 return new KeySet<E>(m.subMap(fromElement, fromInclusive,
2387 toElement, toInclusive));
2388 }
2389 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2390 return new KeySet<E>(m.headMap(toElement, inclusive));
2391 }
2392 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2393 return new KeySet<E>(m.tailMap(fromElement, inclusive));
2394 }
2395 public NavigableSet<E> subSet(E fromElement, E toElement) {
2396 return subSet(fromElement, true, toElement, false);
2397 }
2398 public NavigableSet<E> headSet(E toElement) {
2399 return headSet(toElement, false);
2400 }
2401 public NavigableSet<E> tailSet(E fromElement) {
2402 return tailSet(fromElement, true);
2403 }
2404 public NavigableSet<E> descendingSet() {
2405 return new KeySet<E>(m.descendingMap());
2406 }
2407 @SuppressWarnings("unchecked")
2408 public Spliterator<E> spliterator() {
2409 if (m instanceof ConcurrentSkipListMap)
2410 return ((ConcurrentSkipListMap<E,?>)m).keySpliterator();
2411 else
2412 return (Spliterator<E>)((SubMap<E,?>)m).keyIterator();
2413 }
2414 }
2415
2416 static final class Values<E> extends AbstractCollection<E> {
2417 final ConcurrentNavigableMap<?, E> m;
2418 Values(ConcurrentNavigableMap<?, E> map) {
2419 m = map;
2420 }
2421 @SuppressWarnings("unchecked")
2422 public Iterator<E> iterator() {
2423 if (m instanceof ConcurrentSkipListMap)
2424 return ((ConcurrentSkipListMap<?,E>)m).valueIterator();
2425 else
2426 return ((SubMap<?,E>)m).valueIterator();
2427 }
2428 public boolean isEmpty() {
2429 return m.isEmpty();
2430 }
2431 public int size() {
2432 return m.size();
2433 }
2434 public boolean contains(Object o) {
2435 return m.containsValue(o);
2436 }
2437 public void clear() {
2438 m.clear();
2439 }
2440 public Object[] toArray() { return toList(this).toArray(); }
2441 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2442 @SuppressWarnings("unchecked")
2443 public Spliterator<E> spliterator() {
2444 if (m instanceof ConcurrentSkipListMap)
2445 return ((ConcurrentSkipListMap<?,E>)m).valueSpliterator();
2446 else
2447 return (Spliterator<E>)((SubMap<?,E>)m).valueIterator();
2448 }
2449 }
2450
2451 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2452 final ConcurrentNavigableMap<K1, V1> m;
2453 EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2454 m = map;
2455 }
2456 @SuppressWarnings("unchecked")
2457 public Iterator<Map.Entry<K1,V1>> iterator() {
2458 if (m instanceof ConcurrentSkipListMap)
2459 return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2460 else
2461 return ((SubMap<K1,V1>)m).entryIterator();
2462 }
2463
2464 public boolean contains(Object o) {
2465 if (!(o instanceof Map.Entry))
2466 return false;
2467 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2468 V1 v = m.get(e.getKey());
2469 return v != null && v.equals(e.getValue());
2470 }
2471 public boolean remove(Object o) {
2472 if (!(o instanceof Map.Entry))
2473 return false;
2474 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
2475 return m.remove(e.getKey(),
2476 e.getValue());
2477 }
2478 public boolean isEmpty() {
2479 return m.isEmpty();
2480 }
2481 public int size() {
2482 return m.size();
2483 }
2484 public void clear() {
2485 m.clear();
2486 }
2487 public boolean equals(Object o) {
2488 if (o == this)
2489 return true;
2490 if (!(o instanceof Set))
2491 return false;
2492 Collection<?> c = (Collection<?>) o;
2493 try {
2494 return containsAll(c) && c.containsAll(this);
2495 } catch (ClassCastException unused) {
2496 return false;
2497 } catch (NullPointerException unused) {
2498 return false;
2499 }
2500 }
2501 public Object[] toArray() { return toList(this).toArray(); }
2502 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2503 @SuppressWarnings("unchecked")
2504 public Spliterator<Map.Entry<K1,V1>> spliterator() {
2505 if (m instanceof ConcurrentSkipListMap)
2506 return ((ConcurrentSkipListMap<K1,V1>)m).entrySpliterator();
2507 else
2508 return (Spliterator<Map.Entry<K1,V1>>)
2509 ((SubMap<K1,V1>)m).entryIterator();
2510 }
2511 }
2512
2513 /**
2514 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2515 * represent a subrange of mappings of their underlying
2516 * maps. Instances of this class support all methods of their
2517 * underlying maps, differing in that mappings outside their range are
2518 * ignored, and attempts to add mappings outside their ranges result
2519 * in {@link IllegalArgumentException}. Instances of this class are
2520 * constructed only using the {@code subMap}, {@code headMap}, and
2521 * {@code tailMap} methods of their underlying maps.
2522 *
2523 * @serial include
2524 */
2525 static final class SubMap<K,V> extends AbstractMap<K,V>
2526 implements ConcurrentNavigableMap<K,V>, Cloneable,
2527 java.io.Serializable {
2528 private static final long serialVersionUID = -7647078645895051609L;
2529
2530 /** Underlying map */
2531 private final ConcurrentSkipListMap<K,V> m;
2532 /** lower bound key, or null if from start */
2533 private final K lo;
2534 /** upper bound key, or null if to end */
2535 private final K hi;
2536 /** inclusion flag for lo */
2537 private final boolean loInclusive;
2538 /** inclusion flag for hi */
2539 private final boolean hiInclusive;
2540 /** direction */
2541 private final boolean isDescending;
2542
2543 // Lazily initialized view holders
2544 private transient KeySet<K> keySetView;
2545 private transient Set<Map.Entry<K,V>> entrySetView;
2546 private transient Collection<V> valuesView;
2547
2548 /**
2549 * Creates a new submap, initializing all fields.
2550 */
2551 SubMap(ConcurrentSkipListMap<K,V> map,
2552 K fromKey, boolean fromInclusive,
2553 K toKey, boolean toInclusive,
2554 boolean isDescending) {
2555 Comparator<? super K> cmp = map.comparator;
2556 if (fromKey != null && toKey != null &&
2557 cpr(cmp, fromKey, toKey) > 0)
2558 throw new IllegalArgumentException("inconsistent range");
2559 this.m = map;
2560 this.lo = fromKey;
2561 this.hi = toKey;
2562 this.loInclusive = fromInclusive;
2563 this.hiInclusive = toInclusive;
2564 this.isDescending = isDescending;
2565 }
2566
2567 /* ---------------- Utilities -------------- */
2568
2569 boolean tooLow(Object key, Comparator<? super K> cmp) {
2570 int c;
2571 return (lo != null && ((c = cpr(cmp, key, lo)) < 0 ||
2572 (c == 0 && !loInclusive)));
2573 }
2574
2575 boolean tooHigh(Object key, Comparator<? super K> cmp) {
2576 int c;
2577 return (hi != null && ((c = cpr(cmp, key, hi)) > 0 ||
2578 (c == 0 && !hiInclusive)));
2579 }
2580
2581 boolean inBounds(Object key, Comparator<? super K> cmp) {
2582 return !tooLow(key, cmp) && !tooHigh(key, cmp);
2583 }
2584
2585 void checkKeyBounds(K key, Comparator<? super K> cmp) {
2586 if (key == null)
2587 throw new NullPointerException();
2588 if (!inBounds(key, cmp))
2589 throw new IllegalArgumentException("key out of range");
2590 }
2591
2592 /**
2593 * Returns true if node key is less than upper bound of range.
2594 */
2595 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n,
2596 Comparator<? super K> cmp) {
2597 if (n == null)
2598 return false;
2599 if (hi == null)
2600 return true;
2601 K k = n.key;
2602 if (k == null) // pass by markers and headers
2603 return true;
2604 int c = cpr(cmp, k, hi);
2605 if (c > 0 || (c == 0 && !hiInclusive))
2606 return false;
2607 return true;
2608 }
2609
2610 /**
2611 * Returns lowest node. This node might not be in range, so
2612 * most usages need to check bounds.
2613 */
2614 ConcurrentSkipListMap.Node<K,V> loNode(Comparator<? super K> cmp) {
2615 if (lo == null)
2616 return m.findFirst();
2617 else if (loInclusive)
2618 return m.findNear(lo, GT|EQ, cmp);
2619 else
2620 return m.findNear(lo, GT, cmp);
2621 }
2622
2623 /**
2624 * Returns highest node. This node might not be in range, so
2625 * most usages need to check bounds.
2626 */
2627 ConcurrentSkipListMap.Node<K,V> hiNode(Comparator<? super K> cmp) {
2628 if (hi == null)
2629 return m.findLast();
2630 else if (hiInclusive)
2631 return m.findNear(hi, LT|EQ, cmp);
2632 else
2633 return m.findNear(hi, LT, cmp);
2634 }
2635
2636 /**
2637 * Returns lowest absolute key (ignoring directonality).
2638 */
2639 K lowestKey() {
2640 Comparator<? super K> cmp = m.comparator;
2641 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2642 if (isBeforeEnd(n, cmp))
2643 return n.key;
2644 else
2645 throw new NoSuchElementException();
2646 }
2647
2648 /**
2649 * Returns highest absolute key (ignoring directonality).
2650 */
2651 K highestKey() {
2652 Comparator<? super K> cmp = m.comparator;
2653 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2654 if (n != null) {
2655 K last = n.key;
2656 if (inBounds(last, cmp))
2657 return last;
2658 }
2659 throw new NoSuchElementException();
2660 }
2661
2662 Map.Entry<K,V> lowestEntry() {
2663 Comparator<? super K> cmp = m.comparator;
2664 for (;;) {
2665 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2666 if (!isBeforeEnd(n, cmp))
2667 return null;
2668 Map.Entry<K,V> e = n.createSnapshot();
2669 if (e != null)
2670 return e;
2671 }
2672 }
2673
2674 Map.Entry<K,V> highestEntry() {
2675 Comparator<? super K> cmp = m.comparator;
2676 for (;;) {
2677 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2678 if (n == null || !inBounds(n.key, cmp))
2679 return null;
2680 Map.Entry<K,V> e = n.createSnapshot();
2681 if (e != null)
2682 return e;
2683 }
2684 }
2685
2686 Map.Entry<K,V> removeLowest() {
2687 Comparator<? super K> cmp = m.comparator;
2688 for (;;) {
2689 Node<K,V> n = loNode(cmp);
2690 if (n == null)
2691 return null;
2692 K k = n.key;
2693 if (!inBounds(k, cmp))
2694 return null;
2695 V v = m.doRemove(k, null);
2696 if (v != null)
2697 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2698 }
2699 }
2700
2701 Map.Entry<K,V> removeHighest() {
2702 Comparator<? super K> cmp = m.comparator;
2703 for (;;) {
2704 Node<K,V> n = hiNode(cmp);
2705 if (n == null)
2706 return null;
2707 K k = n.key;
2708 if (!inBounds(k, cmp))
2709 return null;
2710 V v = m.doRemove(k, null);
2711 if (v != null)
2712 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2713 }
2714 }
2715
2716 /**
2717 * Submap version of ConcurrentSkipListMap.getNearEntry
2718 */
2719 Map.Entry<K,V> getNearEntry(K key, int rel) {
2720 Comparator<? super K> cmp = m.comparator;
2721 if (isDescending) { // adjust relation for direction
2722 if ((rel & LT) == 0)
2723 rel |= LT;
2724 else
2725 rel &= ~LT;
2726 }
2727 if (tooLow(key, cmp))
2728 return ((rel & LT) != 0) ? null : lowestEntry();
2729 if (tooHigh(key, cmp))
2730 return ((rel & LT) != 0) ? highestEntry() : null;
2731 for (;;) {
2732 Node<K,V> n = m.findNear(key, rel, cmp);
2733 if (n == null || !inBounds(n.key, cmp))
2734 return null;
2735 K k = n.key;
2736 V v = n.getValidValue();
2737 if (v != null)
2738 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2739 }
2740 }
2741
2742 // Almost the same as getNearEntry, except for keys
2743 K getNearKey(K key, int rel) {
2744 Comparator<? super K> cmp = m.comparator;
2745 if (isDescending) { // adjust relation for direction
2746 if ((rel & LT) == 0)
2747 rel |= LT;
2748 else
2749 rel &= ~LT;
2750 }
2751 if (tooLow(key, cmp)) {
2752 if ((rel & LT) == 0) {
2753 ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2754 if (isBeforeEnd(n, cmp))
2755 return n.key;
2756 }
2757 return null;
2758 }
2759 if (tooHigh(key, cmp)) {
2760 if ((rel & LT) != 0) {
2761 ConcurrentSkipListMap.Node<K,V> n = hiNode(cmp);
2762 if (n != null) {
2763 K last = n.key;
2764 if (inBounds(last, cmp))
2765 return last;
2766 }
2767 }
2768 return null;
2769 }
2770 for (;;) {
2771 Node<K,V> n = m.findNear(key, rel, cmp);
2772 if (n == null || !inBounds(n.key, cmp))
2773 return null;
2774 K k = n.key;
2775 V v = n.getValidValue();
2776 if (v != null)
2777 return k;
2778 }
2779 }
2780
2781 /* ---------------- Map API methods -------------- */
2782
2783 public boolean containsKey(Object key) {
2784 if (key == null) throw new NullPointerException();
2785 return inBounds(key, m.comparator) && m.containsKey(key);
2786 }
2787
2788 public V get(Object key) {
2789 if (key == null) throw new NullPointerException();
2790 return (!inBounds(key, m.comparator)) ? null : m.get(key);
2791 }
2792
2793 public V put(K key, V value) {
2794 checkKeyBounds(key, m.comparator);
2795 return m.put(key, value);
2796 }
2797
2798 public V remove(Object key) {
2799 return (!inBounds(key, m.comparator)) ? null : m.remove(key);
2800 }
2801
2802 public int size() {
2803 Comparator<? super K> cmp = m.comparator;
2804 long count = 0;
2805 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2806 isBeforeEnd(n, cmp);
2807 n = n.next) {
2808 if (n.getValidValue() != null)
2809 ++count;
2810 }
2811 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2812 }
2813
2814 public boolean isEmpty() {
2815 Comparator<? super K> cmp = m.comparator;
2816 return !isBeforeEnd(loNode(cmp), cmp);
2817 }
2818
2819 public boolean containsValue(Object value) {
2820 if (value == null)
2821 throw new NullPointerException();
2822 Comparator<? super K> cmp = m.comparator;
2823 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2824 isBeforeEnd(n, cmp);
2825 n = n.next) {
2826 V v = n.getValidValue();
2827 if (v != null && value.equals(v))
2828 return true;
2829 }
2830 return false;
2831 }
2832
2833 public void clear() {
2834 Comparator<? super K> cmp = m.comparator;
2835 for (ConcurrentSkipListMap.Node<K,V> n = loNode(cmp);
2836 isBeforeEnd(n, cmp);
2837 n = n.next) {
2838 if (n.getValidValue() != null)
2839 m.remove(n.key);
2840 }
2841 }
2842
2843 /* ---------------- ConcurrentMap API methods -------------- */
2844
2845 public V putIfAbsent(K key, V value) {
2846 checkKeyBounds(key, m.comparator);
2847 return m.putIfAbsent(key, value);
2848 }
2849
2850 public boolean remove(Object key, Object value) {
2851 return inBounds(key, m.comparator) && m.remove(key, value);
2852 }
2853
2854 public boolean replace(K key, V oldValue, V newValue) {
2855 checkKeyBounds(key, m.comparator);
2856 return m.replace(key, oldValue, newValue);
2857 }
2858
2859 public V replace(K key, V value) {
2860 checkKeyBounds(key, m.comparator);
2861 return m.replace(key, value);
2862 }
2863
2864 /* ---------------- SortedMap API methods -------------- */
2865
2866 public Comparator<? super K> comparator() {
2867 Comparator<? super K> cmp = m.comparator();
2868 if (isDescending)
2869 return Collections.reverseOrder(cmp);
2870 else
2871 return cmp;
2872 }
2873
2874 /**
2875 * Utility to create submaps, where given bounds override
2876 * unbounded(null) ones and/or are checked against bounded ones.
2877 */
2878 SubMap<K,V> newSubMap(K fromKey, boolean fromInclusive,
2879 K toKey, boolean toInclusive) {
2880 Comparator<? super K> cmp = m.comparator;
2881 if (isDescending) { // flip senses
2882 K tk = fromKey;
2883 fromKey = toKey;
2884 toKey = tk;
2885 boolean ti = fromInclusive;
2886 fromInclusive = toInclusive;
2887 toInclusive = ti;
2888 }
2889 if (lo != null) {
2890 if (fromKey == null) {
2891 fromKey = lo;
2892 fromInclusive = loInclusive;
2893 }
2894 else {
2895 int c = cpr(cmp, fromKey, lo);
2896 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2897 throw new IllegalArgumentException("key out of range");
2898 }
2899 }
2900 if (hi != null) {
2901 if (toKey == null) {
2902 toKey = hi;
2903 toInclusive = hiInclusive;
2904 }
2905 else {
2906 int c = cpr(cmp, toKey, hi);
2907 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2908 throw new IllegalArgumentException("key out of range");
2909 }
2910 }
2911 return new SubMap<K,V>(m, fromKey, fromInclusive,
2912 toKey, toInclusive, isDescending);
2913 }
2914
2915 public SubMap<K,V> subMap(K fromKey, boolean fromInclusive,
2916 K toKey, boolean toInclusive) {
2917 if (fromKey == null || toKey == null)
2918 throw new NullPointerException();
2919 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2920 }
2921
2922 public SubMap<K,V> headMap(K toKey, boolean inclusive) {
2923 if (toKey == null)
2924 throw new NullPointerException();
2925 return newSubMap(null, false, toKey, inclusive);
2926 }
2927
2928 public SubMap<K,V> tailMap(K fromKey, boolean inclusive) {
2929 if (fromKey == null)
2930 throw new NullPointerException();
2931 return newSubMap(fromKey, inclusive, null, false);
2932 }
2933
2934 public SubMap<K,V> subMap(K fromKey, K toKey) {
2935 return subMap(fromKey, true, toKey, false);
2936 }
2937
2938 public SubMap<K,V> headMap(K toKey) {
2939 return headMap(toKey, false);
2940 }
2941
2942 public SubMap<K,V> tailMap(K fromKey) {
2943 return tailMap(fromKey, true);
2944 }
2945
2946 public SubMap<K,V> descendingMap() {
2947 return new SubMap<K,V>(m, lo, loInclusive,
2948 hi, hiInclusive, !isDescending);
2949 }
2950
2951 /* ---------------- Relational methods -------------- */
2952
2953 public Map.Entry<K,V> ceilingEntry(K key) {
2954 return getNearEntry(key, GT|EQ);
2955 }
2956
2957 public K ceilingKey(K key) {
2958 return getNearKey(key, GT|EQ);
2959 }
2960
2961 public Map.Entry<K,V> lowerEntry(K key) {
2962 return getNearEntry(key, LT);
2963 }
2964
2965 public K lowerKey(K key) {
2966 return getNearKey(key, LT);
2967 }
2968
2969 public Map.Entry<K,V> floorEntry(K key) {
2970 return getNearEntry(key, LT|EQ);
2971 }
2972
2973 public K floorKey(K key) {
2974 return getNearKey(key, LT|EQ);
2975 }
2976
2977 public Map.Entry<K,V> higherEntry(K key) {
2978 return getNearEntry(key, GT);
2979 }
2980
2981 public K higherKey(K key) {
2982 return getNearKey(key, GT);
2983 }
2984
2985 public K firstKey() {
2986 return isDescending ? highestKey() : lowestKey();
2987 }
2988
2989 public K lastKey() {
2990 return isDescending ? lowestKey() : highestKey();
2991 }
2992
2993 public Map.Entry<K,V> firstEntry() {
2994 return isDescending ? highestEntry() : lowestEntry();
2995 }
2996
2997 public Map.Entry<K,V> lastEntry() {
2998 return isDescending ? lowestEntry() : highestEntry();
2999 }
3000
3001 public Map.Entry<K,V> pollFirstEntry() {
3002 return isDescending ? removeHighest() : removeLowest();
3003 }
3004
3005 public Map.Entry<K,V> pollLastEntry() {
3006 return isDescending ? removeLowest() : removeHighest();
3007 }
3008
3009 /* ---------------- Submap Views -------------- */
3010
3011 public NavigableSet<K> keySet() {
3012 KeySet<K> ks = keySetView;
3013 return (ks != null) ? ks : (keySetView = new KeySet<K>(this));
3014 }
3015
3016 public NavigableSet<K> navigableKeySet() {
3017 KeySet<K> ks = keySetView;
3018 return (ks != null) ? ks : (keySetView = new KeySet<K>(this));
3019 }
3020
3021 public Collection<V> values() {
3022 Collection<V> vs = valuesView;
3023 return (vs != null) ? vs : (valuesView = new Values<V>(this));
3024 }
3025
3026 public Set<Map.Entry<K,V>> entrySet() {
3027 Set<Map.Entry<K,V>> es = entrySetView;
3028 return (es != null) ? es : (entrySetView = new EntrySet<K,V>(this));
3029 }
3030
3031 public NavigableSet<K> descendingKeySet() {
3032 return descendingMap().navigableKeySet();
3033 }
3034
3035 Iterator<K> keyIterator() {
3036 return new SubMapKeyIterator();
3037 }
3038
3039 Iterator<V> valueIterator() {
3040 return new SubMapValueIterator();
3041 }
3042
3043 Iterator<Map.Entry<K,V>> entryIterator() {
3044 return new SubMapEntryIterator();
3045 }
3046
3047 /**
3048 * Variant of main Iter class to traverse through submaps.
3049 * Also serves as back-up Spliterator for views
3050 */
3051 abstract class SubMapIter<T> implements Iterator<T>, Spliterator<T> {
3052 /** the last node returned by next() */
3053 Node<K,V> lastReturned;
3054 /** the next node to return from next(); */
3055 Node<K,V> next;
3056 /** Cache of next value field to maintain weak consistency */
3057 V nextValue;
3058
3059 SubMapIter() {
3060 Comparator<? super K> cmp = m.comparator;
3061 for (;;) {
3062 next = isDescending ? hiNode(cmp) : loNode(cmp);
3063 if (next == null)
3064 break;
3065 Object x = next.value;
3066 if (x != null && x != next) {
3067 if (! inBounds(next.key, cmp))
3068 next = null;
3069 else {
3070 @SuppressWarnings("unchecked") V vv = (V)x;
3071 nextValue = vv;
3072 }
3073 break;
3074 }
3075 }
3076 }
3077
3078 public final boolean hasNext() {
3079 return next != null;
3080 }
3081
3082 final void advance() {
3083 if (next == null)
3084 throw new NoSuchElementException();
3085 lastReturned = next;
3086 if (isDescending)
3087 descend();
3088 else
3089 ascend();
3090 }
3091
3092 private void ascend() {
3093 Comparator<? super K> cmp = m.comparator;
3094 for (;;) {
3095 next = next.next;
3096 if (next == null)
3097 break;
3098 Object x = next.value;
3099 if (x != null && x != next) {
3100 if (tooHigh(next.key, cmp))
3101 next = null;
3102 else {
3103 @SuppressWarnings("unchecked") V vv = (V)x;
3104 nextValue = vv;
3105 }
3106 break;
3107 }
3108 }
3109 }
3110
3111 private void descend() {
3112 Comparator<? super K> cmp = m.comparator;
3113 for (;;) {
3114 next = m.findNear(lastReturned.key, LT, cmp);
3115 if (next == null)
3116 break;
3117 Object x = next.value;
3118 if (x != null && x != next) {
3119 if (tooLow(next.key, cmp))
3120 next = null;
3121 else {
3122 @SuppressWarnings("unchecked") V vv = (V)x;
3123 nextValue = vv;
3124 }
3125 break;
3126 }
3127 }
3128 }
3129
3130 public void remove() {
3131 Node<K,V> l = lastReturned;
3132 if (l == null)
3133 throw new IllegalStateException();
3134 m.remove(l.key);
3135 lastReturned = null;
3136 }
3137
3138 public Spliterator<T> trySplit() {
3139 return null;
3140 }
3141
3142 public boolean tryAdvance(Consumer<? super T> action) {
3143 if (hasNext()) {
3144 action.accept(next());
3145 return true;
3146 }
3147 return false;
3148 }
3149
3150 public void forEachRemaining(Consumer<? super T> action) {
3151 while (hasNext())
3152 action.accept(next());
3153 }
3154
3155 public long estimateSize() {
3156 return Long.MAX_VALUE;
3157 }
3158
3159 }
3160
3161 final class SubMapValueIterator extends SubMapIter<V> {
3162 public V next() {
3163 V v = nextValue;
3164 advance();
3165 return v;
3166 }
3167 public int characteristics() {
3168 return 0;
3169 }
3170 }
3171
3172 final class SubMapKeyIterator extends SubMapIter<K> {
3173 public K next() {
3174 Node<K,V> n = next;
3175 advance();
3176 return n.key;
3177 }
3178 public int characteristics() {
3179 return Spliterator.DISTINCT | Spliterator.ORDERED |
3180 Spliterator.SORTED;
3181 }
3182 public final Comparator<? super K> getComparator() {
3183 return SubMap.this.comparator();
3184 }
3185 }
3186
3187 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3188 public Map.Entry<K,V> next() {
3189 Node<K,V> n = next;
3190 V v = nextValue;
3191 advance();
3192 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3193 }
3194 public int characteristics() {
3195 return Spliterator.DISTINCT;
3196 }
3197 }
3198 }
3199
3200 // default Map method overrides
3201
3202 public void forEach(BiConsumer<? super K, ? super V> action) {
3203 if (action == null) throw new NullPointerException();
3204 V v;
3205 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3206 if ((v = n.getValidValue()) != null)
3207 action.accept(n.key, v);
3208 }
3209 }
3210
3211 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3212 if (function == null) throw new NullPointerException();
3213 V v;
3214 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
3215 while ((v = n.getValidValue()) != null) {
3216 V r = function.apply(n.key, v);
3217 if (r == null) throw new NullPointerException();
3218 if (n.casValue(v, r))
3219 break;
3220 }
3221 }
3222 }
3223
3224 /**
3225 * Base class providing common structure for Spliterators.
3226 * (Although not all that much common functionality; as usual for
3227 * view classes, details annoyingly vary in key, value, and entry
3228 * subclasses in ways that are not worth abstracting out for
3229 * internal classes.)
3230 *
3231 * The basic split strategy is to recursively descend from top
3232 * level, row by row, descending to next row when either split
3233 * off, or the end of row is encountered. Control of the number of
3234 * splits relies on some statistical estimation: The expected
3235 * remaining number of elements of a skip list when advancing
3236 * either across or down decreases by about 25%. To make this
3237 * observation useful, we need to know initial size, which we
3238 * don't. But we can just use Integer.MAX_VALUE so that we
3239 * don't prematurely zero out while splitting.
3240 */
3241 abstract static class CSLMSpliterator<K,V> {
3242 final Comparator<? super K> comparator;
3243 final K fence; // exclusive upper bound for keys, or null if to end
3244 Index<K,V> row; // the level to split out
3245 Node<K,V> current; // current traversal node; initialize at origin
3246 int est; // pseudo-size estimate
3247 CSLMSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3248 Node<K,V> origin, K fence, int est) {
3249 this.comparator = comparator; this.row = row;
3250 this.current = origin; this.fence = fence; this.est = est;
3251 }
3252
3253 public final long estimateSize() { return (long)est; }
3254 }
3255
3256 static final class KeySpliterator<K,V> extends CSLMSpliterator<K,V>
3257 implements Spliterator<K> {
3258 KeySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3259 Node<K,V> origin, K fence, int est) {
3260 super(comparator, row, origin, fence, est);
3261 }
3262
3263 public Spliterator<K> trySplit() {
3264 Node<K,V> e; K ek;
3265 Comparator<? super K> cmp = comparator;
3266 K f = fence;
3267 if ((e = current) != null && (ek = e.key) != null) {
3268 for (Index<K,V> q = row; q != null; q = row = q.down) {
3269 Index<K,V> s; Node<K,V> b, n; K sk;
3270 if ((s = q.right) != null && (b = s.node) != null &&
3271 (n = b.next) != null && n.value != null &&
3272 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3273 (f == null || cpr(cmp, sk, f) < 0)) {
3274 current = n;
3275 Index<K,V> r = q.down;
3276 row = (s.right != null) ? s : s.down;
3277 est -= est >>> 2;
3278 return new KeySpliterator<K,V>(cmp, r, e, sk, est);
3279 }
3280 }
3281 }
3282 return null;
3283 }
3284
3285 public void forEachRemaining(Consumer<? super K> action) {
3286 if (action == null) throw new NullPointerException();
3287 Comparator<? super K> cmp = comparator;
3288 K f = fence;
3289 Node<K,V> e = current;
3290 current = null;
3291 for (; e != null; e = e.next) {
3292 K k; Object v;
3293 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3294 break;
3295 if ((v = e.value) != null && v != e)
3296 action.accept(k);
3297 }
3298 }
3299
3300 public boolean tryAdvance(Consumer<? super K> action) {
3301 if (action == null) throw new NullPointerException();
3302 Comparator<? super K> cmp = comparator;
3303 K f = fence;
3304 Node<K,V> e = current;
3305 for (; e != null; e = e.next) {
3306 K k; Object v;
3307 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3308 e = null;
3309 break;
3310 }
3311 if ((v = e.value) != null && v != e) {
3312 current = e.next;
3313 action.accept(k);
3314 return true;
3315 }
3316 }
3317 current = e;
3318 return false;
3319 }
3320
3321 public int characteristics() {
3322 return Spliterator.DISTINCT | Spliterator.SORTED |
3323 Spliterator.ORDERED | Spliterator.CONCURRENT |
3324 Spliterator.NONNULL;
3325 }
3326
3327 public final Comparator<? super K> getComparator() {
3328 return comparator;
3329 }
3330 }
3331 // factory method for KeySpliterator
3332 final KeySpliterator<K,V> keySpliterator() {
3333 Comparator<? super K> cmp = comparator;
3334 for (;;) { // ensure h corresponds to origin p
3335 HeadIndex<K,V> h; Node<K,V> p;
3336 Node<K,V> b = (h = head).node;
3337 if ((p = b.next) == null || p.value != null)
3338 return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3339 0 : Integer.MAX_VALUE);
3340 p.helpDelete(b, p.next);
3341 }
3342 }
3343
3344 static final class ValueSpliterator<K,V> extends CSLMSpliterator<K,V>
3345 implements Spliterator<V> {
3346 ValueSpliterator(Comparator<? super K> comparator, Index<K,V> row,
3347 Node<K,V> origin, K fence, int est) {
3348 super(comparator, row, origin, fence, est);
3349 }
3350
3351 public Spliterator<V> trySplit() {
3352 Node<K,V> e; K ek;
3353 Comparator<? super K> cmp = comparator;
3354 K f = fence;
3355 if ((e = current) != null && (ek = e.key) != null) {
3356 for (Index<K,V> q = row; q != null; q = row = q.down) {
3357 Index<K,V> s; Node<K,V> b, n; K sk;
3358 if ((s = q.right) != null && (b = s.node) != null &&
3359 (n = b.next) != null && n.value != null &&
3360 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3361 (f == null || cpr(cmp, sk, f) < 0)) {
3362 current = n;
3363 Index<K,V> r = q.down;
3364 row = (s.right != null) ? s : s.down;
3365 est -= est >>> 2;
3366 return new ValueSpliterator<K,V>(cmp, r, e, sk, est);
3367 }
3368 }
3369 }
3370 return null;
3371 }
3372
3373 public void forEachRemaining(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 current = null;
3379 for (; e != null; e = e.next) {
3380 K k; Object v;
3381 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
3382 break;
3383 if ((v = e.value) != null && v != e) {
3384 @SuppressWarnings("unchecked") V vv = (V)v;
3385 action.accept(vv);
3386 }
3387 }
3388 }
3389
3390 public boolean tryAdvance(Consumer<? super V> action) {
3391 if (action == null) throw new NullPointerException();
3392 Comparator<? super K> cmp = comparator;
3393 K f = fence;
3394 Node<K,V> e = current;
3395 for (; e != null; e = e.next) {
3396 K k; Object v;
3397 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3398 e = null;
3399 break;
3400 }
3401 if ((v = e.value) != null && v != e) {
3402 current = e.next;
3403 @SuppressWarnings("unchecked") V vv = (V)v;
3404 action.accept(vv);
3405 return true;
3406 }
3407 }
3408 current = e;
3409 return false;
3410 }
3411
3412 public int characteristics() {
3413 return Spliterator.CONCURRENT | Spliterator.NONNULL;
3414 }
3415 }
3416
3417 // Almost the same as keySpliterator()
3418 final ValueSpliterator<K,V> valueSpliterator() {
3419 Comparator<? super K> cmp = comparator;
3420 for (;;) {
3421 HeadIndex<K,V> h; Node<K,V> p;
3422 Node<K,V> b = (h = head).node;
3423 if ((p = b.next) == null || p.value != null)
3424 return new ValueSpliterator<K,V>(cmp, h, p, null, (p == null) ?
3425 0 : Integer.MAX_VALUE);
3426 p.helpDelete(b, p.next);
3427 }
3428 }
3429
3430 static final class EntrySpliterator<K,V> extends CSLMSpliterator<K,V>
3431 implements Spliterator<Map.Entry<K,V>> {
3432 EntrySpliterator(Comparator<? super K> comparator, Index<K,V> row,
3433 Node<K,V> origin, K fence, int est) {
3434 super(comparator, row, origin, fence, est);
3435 }
3436
3437 public Spliterator<Map.Entry<K,V>> trySplit() {
3438 Node<K,V> e; K ek;
3439 Comparator<? super K> cmp = comparator;
3440 K f = fence;
3441 if ((e = current) != null && (ek = e.key) != null) {
3442 for (Index<K,V> q = row; q != null; q = row = q.down) {
3443 Index<K,V> s; Node<K,V> b, n; K sk;
3444 if ((s = q.right) != null && (b = s.node) != null &&
3445 (n = b.next) != null && n.value != null &&
3446 (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
3447 (f == null || cpr(cmp, sk, f) < 0)) {
3448 current = n;
3449 Index<K,V> r = q.down;
3450 row = (s.right != null) ? s : s.down;
3451 est -= est >>> 2;
3452 return new EntrySpliterator<K,V>(cmp, r, e, sk, est);
3453 }
3454 }
3455 }
3456 return null;
3457 }
3458
3459 public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
3460 if (action == null) throw new NullPointerException();
3461 Comparator<? super K> cmp = comparator;
3462 K f = fence;
3463 Node<K,V> e = current;
3464 current = null;
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 break;
3469 if ((v = e.value) != null && v != e) {
3470 @SuppressWarnings("unchecked") V vv = (V)v;
3471 action.accept
3472 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3473 }
3474 }
3475 }
3476
3477 public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
3478 if (action == null) throw new NullPointerException();
3479 Comparator<? super K> cmp = comparator;
3480 K f = fence;
3481 Node<K,V> e = current;
3482 for (; e != null; e = e.next) {
3483 K k; Object v;
3484 if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
3485 e = null;
3486 break;
3487 }
3488 if ((v = e.value) != null && v != e) {
3489 current = e.next;
3490 @SuppressWarnings("unchecked") V vv = (V)v;
3491 action.accept
3492 (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
3493 return true;
3494 }
3495 }
3496 current = e;
3497 return false;
3498 }
3499
3500 public int characteristics() {
3501 return Spliterator.DISTINCT | Spliterator.SORTED |
3502 Spliterator.ORDERED | Spliterator.CONCURRENT |
3503 Spliterator.NONNULL;
3504 }
3505
3506 public final Comparator<Map.Entry<K,V>> getComparator() {
3507 return comparator == null ? null :
3508 Entry.comparingByKey(comparator);
3509 }
3510 }
3511
3512 // Almost the same as keySpliterator()
3513 final EntrySpliterator<K,V> entrySpliterator() {
3514 Comparator<? super K> cmp = comparator;
3515 for (;;) { // almost same as key version
3516 HeadIndex<K,V> h; Node<K,V> p;
3517 Node<K,V> b = (h = head).node;
3518 if ((p = b.next) == null || p.value != null)
3519 return new EntrySpliterator<K,V>(cmp, h, p, null, (p == null) ?
3520 0 : Integer.MAX_VALUE);
3521 p.helpDelete(b, p.next);
3522 }
3523 }
3524
3525 // Unsafe mechanics
3526 private static final sun.misc.Unsafe UNSAFE;
3527 private static final long headOffset;
3528 private static final long SECONDARY;
3529 static {
3530 try {
3531 UNSAFE = sun.misc.Unsafe.getUnsafe();
3532 Class<?> k = ConcurrentSkipListMap.class;
3533 headOffset = UNSAFE.objectFieldOffset
3534 (k.getDeclaredField("head"));
3535 Class<?> tk = Thread.class;
3536 SECONDARY = UNSAFE.objectFieldOffset
3537 (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
3538
3539 } catch (Exception e) {
3540 throw new Error(e);
3541 }
3542 }
3543 }