ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.13
Committed: Thu Sep 3 22:54:46 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.12: +1 -1 lines
Log Message:
s/adaptor/adapter/g

File Contents

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