ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.67
Committed: Tue Mar 15 19:47:03 2011 UTC (13 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.66: +1 -1 lines
Log Message:
Update Creative Commons license URL in legal notices

File Contents

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