ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.61
Committed: Fri Oct 22 05:18:30 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +22 -22 lines
Log Message:
whitespace

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/licenses/publicdomain
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://www.cs.umd.edu/~pugh/">SkipLists</a> providing
19 * 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 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
483 private static final long valueOffset =
484 objectFieldOffset(UNSAFE, "value", Node.class);
485 private static final long nextOffset =
486 objectFieldOffset(UNSAFE, "next", Node.class);
487
488 }
489
490 /* ---------------- Indexing -------------- */
491
492 /**
493 * Index nodes represent the levels of the skip list. Note that
494 * even though both Nodes and Indexes have forward-pointing
495 * fields, they have different types and are handled in different
496 * ways, that can't nicely be captured by placing field in a
497 * shared abstract class.
498 */
499 static class Index<K,V> {
500 final Node<K,V> node;
501 final Index<K,V> down;
502 volatile Index<K,V> right;
503
504 /**
505 * Creates index node with given values.
506 */
507 Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
508 this.node = node;
509 this.down = down;
510 this.right = right;
511 }
512
513 /**
514 * compareAndSet right field
515 */
516 final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
517 return UNSAFE.compareAndSwapObject(this, rightOffset, cmp, val);
518 }
519
520 /**
521 * Returns true if the node this indexes has been deleted.
522 * @return true if indexed node is known to be deleted
523 */
524 final boolean indexesDeletedNode() {
525 return node.value == null;
526 }
527
528 /**
529 * Tries to CAS newSucc as successor. To minimize races with
530 * unlink that may lose this index node, if the node being
531 * indexed is known to be deleted, it doesn't try to link in.
532 * @param succ the expected current successor
533 * @param newSucc the new successor
534 * @return true if successful
535 */
536 final boolean link(Index<K,V> succ, Index<K,V> newSucc) {
537 Node<K,V> n = node;
538 newSucc.right = succ;
539 return n.value != null && casRight(succ, newSucc);
540 }
541
542 /**
543 * Tries to CAS right field to skip over apparent successor
544 * succ. Fails (forcing a retraversal by caller) if this node
545 * is known to be deleted.
546 * @param succ the expected current successor
547 * @return true if successful
548 */
549 final boolean unlink(Index<K,V> succ) {
550 return !indexesDeletedNode() && casRight(succ, succ.right);
551 }
552
553 // Unsafe mechanics
554 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
555 private static final long rightOffset =
556 objectFieldOffset(UNSAFE, "right", Index.class);
557
558 }
559
560 /* ---------------- Head nodes -------------- */
561
562 /**
563 * Nodes heading each level keep track of their level.
564 */
565 static final class HeadIndex<K,V> extends Index<K,V> {
566 final int level;
567 HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) {
568 super(node, down, right);
569 this.level = level;
570 }
571 }
572
573 /* ---------------- Comparison utilities -------------- */
574
575 /**
576 * Represents a key with a comparator as a Comparable.
577 *
578 * Because most sorted collections seem to use natural ordering on
579 * Comparables (Strings, Integers, etc), most internal methods are
580 * geared to use them. This is generally faster than checking
581 * per-comparison whether to use comparator or comparable because
582 * it doesn't require a (Comparable) cast for each comparison.
583 * (Optimizers can only sometimes remove such redundant checks
584 * themselves.) When Comparators are used,
585 * ComparableUsingComparators are created so that they act in the
586 * same way as natural orderings. This penalizes use of
587 * Comparators vs Comparables, which seems like the right
588 * tradeoff.
589 */
590 static final class ComparableUsingComparator<K> implements Comparable<K> {
591 final K actualKey;
592 final Comparator<? super K> cmp;
593 ComparableUsingComparator(K key, Comparator<? super K> cmp) {
594 this.actualKey = key;
595 this.cmp = cmp;
596 }
597 public int compareTo(K k2) {
598 return cmp.compare(actualKey, k2);
599 }
600 }
601
602 /**
603 * If using comparator, return a ComparableUsingComparator, else
604 * cast key as Comparable, which may cause ClassCastException,
605 * which is propagated back to caller.
606 */
607 private Comparable<? super K> comparable(Object key) throws ClassCastException {
608 if (key == null)
609 throw new NullPointerException();
610 if (comparator != null)
611 return new ComparableUsingComparator<K>((K)key, comparator);
612 else
613 return (Comparable<? super K>)key;
614 }
615
616 /**
617 * Compares using comparator or natural ordering. Used when the
618 * ComparableUsingComparator approach doesn't apply.
619 */
620 int compare(K k1, K k2) throws ClassCastException {
621 Comparator<? super K> cmp = comparator;
622 if (cmp != null)
623 return cmp.compare(k1, k2);
624 else
625 return ((Comparable<? super K>)k1).compareTo(k2);
626 }
627
628 /**
629 * Returns true if given key greater than or equal to least and
630 * strictly less than fence, bypassing either test if least or
631 * fence are null. Needed mainly in submap operations.
632 */
633 boolean inHalfOpenRange(K key, K least, K fence) {
634 if (key == null)
635 throw new NullPointerException();
636 return ((least == null || compare(key, least) >= 0) &&
637 (fence == null || compare(key, fence) < 0));
638 }
639
640 /**
641 * Returns true if given key greater than or equal to least and less
642 * or equal to fence. Needed mainly in submap operations.
643 */
644 boolean inOpenRange(K key, K least, K fence) {
645 if (key == null)
646 throw new NullPointerException();
647 return ((least == null || compare(key, least) >= 0) &&
648 (fence == null || compare(key, fence) <= 0));
649 }
650
651 /* ---------------- Traversal -------------- */
652
653 /**
654 * Returns a base-level node with key strictly less than given key,
655 * or the base-level header if there is no such node. Also
656 * unlinks indexes to deleted nodes found along the way. Callers
657 * rely on this side-effect of clearing indices to deleted nodes.
658 * @param key the key
659 * @return a predecessor of key
660 */
661 private Node<K,V> findPredecessor(Comparable<? super K> key) {
662 if (key == null)
663 throw new NullPointerException(); // don't postpone errors
664 for (;;) {
665 Index<K,V> q = head;
666 Index<K,V> r = q.right;
667 for (;;) {
668 if (r != null) {
669 Node<K,V> n = r.node;
670 K k = n.key;
671 if (n.value == null) {
672 if (!q.unlink(r))
673 break; // restart
674 r = q.right; // reread r
675 continue;
676 }
677 if (key.compareTo(k) > 0) {
678 q = r;
679 r = r.right;
680 continue;
681 }
682 }
683 Index<K,V> d = q.down;
684 if (d != null) {
685 q = d;
686 r = d.right;
687 } else
688 return q.node;
689 }
690 }
691 }
692
693 /**
694 * Returns node holding key or null if no such, clearing out any
695 * deleted nodes seen along the way. Repeatedly traverses at
696 * base-level looking for key starting at predecessor returned
697 * from findPredecessor, processing base-level deletions as
698 * encountered. Some callers rely on this side-effect of clearing
699 * deleted nodes.
700 *
701 * Restarts occur, at traversal step centered on node n, if:
702 *
703 * (1) After reading n's next field, n is no longer assumed
704 * predecessor b's current successor, which means that
705 * we don't have a consistent 3-node snapshot and so cannot
706 * unlink any subsequent deleted nodes encountered.
707 *
708 * (2) n's value field is null, indicating n is deleted, in
709 * which case we help out an ongoing structural deletion
710 * before retrying. Even though there are cases where such
711 * unlinking doesn't require restart, they aren't sorted out
712 * here because doing so would not usually outweigh cost of
713 * restarting.
714 *
715 * (3) n is a marker or n's predecessor's value field is null,
716 * indicating (among other possibilities) that
717 * findPredecessor returned a deleted node. We can't unlink
718 * the node because we don't know its predecessor, so rely
719 * on another call to findPredecessor to notice and return
720 * some earlier predecessor, which it will do. This check is
721 * only strictly needed at beginning of loop, (and the
722 * b.value check isn't strictly needed at all) but is done
723 * each iteration to help avoid contention with other
724 * threads by callers that will fail to be able to change
725 * links, and so will retry anyway.
726 *
727 * The traversal loops in doPut, doRemove, and findNear all
728 * include the same three kinds of checks. And specialized
729 * versions appear in findFirst, and findLast and their
730 * variants. They can't easily share code because each uses the
731 * reads of fields held in locals occurring in the orders they
732 * were performed.
733 *
734 * @param key the key
735 * @return node holding key, or null if no such
736 */
737 private Node<K,V> findNode(Comparable<? super K> key) {
738 for (;;) {
739 Node<K,V> b = findPredecessor(key);
740 Node<K,V> n = b.next;
741 for (;;) {
742 if (n == null)
743 return null;
744 Node<K,V> f = n.next;
745 if (n != b.next) // inconsistent read
746 break;
747 Object v = n.value;
748 if (v == null) { // n is deleted
749 n.helpDelete(b, f);
750 break;
751 }
752 if (v == n || b.value == null) // b is deleted
753 break;
754 int c = key.compareTo(n.key);
755 if (c == 0)
756 return n;
757 if (c < 0)
758 return null;
759 b = n;
760 n = f;
761 }
762 }
763 }
764
765 /**
766 * Specialized variant of findNode to perform Map.get. Does a weak
767 * traversal, not bothering to fix any deleted index nodes,
768 * returning early if it happens to see key in index, and passing
769 * over any deleted base nodes, falling back to getUsingFindNode
770 * only if it would otherwise return value from an ongoing
771 * deletion. Also uses "bound" to eliminate need for some
772 * comparisons (see Pugh Cookbook). Also folds uses of null checks
773 * and node-skipping because markers have null keys.
774 * @param okey the key
775 * @return the value, or null if absent
776 */
777 private V doGet(Object okey) {
778 Comparable<? super K> key = comparable(okey);
779 Node<K,V> bound = null;
780 Index<K,V> q = head;
781 Index<K,V> r = q.right;
782 Node<K,V> n;
783 K k;
784 int c;
785 for (;;) {
786 Index<K,V> d;
787 // Traverse rights
788 if (r != null && (n = r.node) != bound && (k = n.key) != null) {
789 if ((c = key.compareTo(k)) > 0) {
790 q = r;
791 r = r.right;
792 continue;
793 } else if (c == 0) {
794 Object v = n.value;
795 return (v != null) ? (V)v : getUsingFindNode(key);
796 } else
797 bound = n;
798 }
799
800 // Traverse down
801 if ((d = q.down) != null) {
802 q = d;
803 r = d.right;
804 } else
805 break;
806 }
807
808 // Traverse nexts
809 for (n = q.node.next; n != null; n = n.next) {
810 if ((k = n.key) != null) {
811 if ((c = key.compareTo(k)) == 0) {
812 Object v = n.value;
813 return (v != null) ? (V)v : getUsingFindNode(key);
814 } else if (c < 0)
815 break;
816 }
817 }
818 return null;
819 }
820
821 /**
822 * Performs map.get via findNode. Used as a backup if doGet
823 * encounters an in-progress deletion.
824 * @param key the key
825 * @return the value, or null if absent
826 */
827 private V getUsingFindNode(Comparable<? super K> key) {
828 /*
829 * Loop needed here and elsewhere in case value field goes
830 * null just as it is about to be returned, in which case we
831 * lost a race with a deletion, so must retry.
832 */
833 for (;;) {
834 Node<K,V> n = findNode(key);
835 if (n == null)
836 return null;
837 Object v = n.value;
838 if (v != null)
839 return (V)v;
840 }
841 }
842
843 /* ---------------- Insertion -------------- */
844
845 /**
846 * Main insertion method. Adds element if not present, or
847 * replaces value if present and onlyIfAbsent is false.
848 * @param kkey the key
849 * @param value the value that must be associated with key
850 * @param onlyIfAbsent if should not insert if already present
851 * @return the old value, or null if newly inserted
852 */
853 private V doPut(K kkey, V value, boolean onlyIfAbsent) {
854 Comparable<? super K> key = comparable(kkey);
855 for (;;) {
856 Node<K,V> b = findPredecessor(key);
857 Node<K,V> n = b.next;
858 for (;;) {
859 if (n != null) {
860 Node<K,V> f = n.next;
861 if (n != b.next) // inconsistent read
862 break;
863 Object v = n.value;
864 if (v == null) { // n is deleted
865 n.helpDelete(b, f);
866 break;
867 }
868 if (v == n || b.value == null) // b is deleted
869 break;
870 int c = key.compareTo(n.key);
871 if (c > 0) {
872 b = n;
873 n = f;
874 continue;
875 }
876 if (c == 0) {
877 if (onlyIfAbsent || n.casValue(v, value))
878 return (V)v;
879 else
880 break; // restart if lost race to replace value
881 }
882 // else c < 0; fall through
883 }
884
885 Node<K,V> z = new Node<K,V>(kkey, value, n);
886 if (!b.casNext(n, z))
887 break; // restart if lost race to append to b
888 int level = randomLevel();
889 if (level > 0)
890 insertIndex(z, level);
891 return null;
892 }
893 }
894 }
895
896 /**
897 * Returns a random level for inserting a new node.
898 * Hardwired to k=1, p=0.5, max 31 (see above and
899 * Pugh's "Skip List Cookbook", sec 3.4).
900 *
901 * This uses the simplest of the generators described in George
902 * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality
903 * generator but is acceptable here.
904 */
905 private int randomLevel() {
906 int x = randomSeed;
907 x ^= x << 13;
908 x ^= x >>> 17;
909 randomSeed = x ^= x << 5;
910 if ((x & 0x80000001) != 0) // test highest and lowest bits
911 return 0;
912 int level = 1;
913 while (((x >>>= 1) & 1) != 0) ++level;
914 return level;
915 }
916
917 /**
918 * Creates and adds index nodes for the given node.
919 * @param z the node
920 * @param level the level of the index
921 */
922 private void insertIndex(Node<K,V> z, int level) {
923 HeadIndex<K,V> h = head;
924 int max = h.level;
925
926 if (level <= max) {
927 Index<K,V> idx = null;
928 for (int i = 1; i <= level; ++i)
929 idx = new Index<K,V>(z, idx, null);
930 addIndex(idx, h, level);
931
932 } else { // Add a new level
933 /*
934 * To reduce interference by other threads checking for
935 * empty levels in tryReduceLevel, new levels are added
936 * with initialized right pointers. Which in turn requires
937 * keeping levels in an array to access them while
938 * creating new head index nodes from the opposite
939 * direction.
940 */
941 level = max + 1;
942 Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
943 Index<K,V> idx = null;
944 for (int i = 1; i <= level; ++i)
945 idxs[i] = idx = new Index<K,V>(z, idx, null);
946
947 HeadIndex<K,V> oldh;
948 int k;
949 for (;;) {
950 oldh = head;
951 int oldLevel = oldh.level;
952 if (level <= oldLevel) { // lost race to add level
953 k = level;
954 break;
955 }
956 HeadIndex<K,V> newh = oldh;
957 Node<K,V> oldbase = oldh.node;
958 for (int j = oldLevel+1; j <= level; ++j)
959 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
960 if (casHead(oldh, newh)) {
961 k = oldLevel;
962 break;
963 }
964 }
965 addIndex(idxs[k], oldh, k);
966 }
967 }
968
969 /**
970 * Adds given index nodes from given level down to 1.
971 * @param idx the topmost index node being inserted
972 * @param h the value of head to use to insert. This must be
973 * snapshotted by callers to provide correct insertion level
974 * @param indexLevel the level of the index
975 */
976 private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
977 // Track next level to insert in case of retries
978 int insertionLevel = indexLevel;
979 Comparable<? super K> key = comparable(idx.node.key);
980 if (key == null) throw new NullPointerException();
981
982 // Similar to findPredecessor, but adding index nodes along
983 // path to key.
984 for (;;) {
985 int j = h.level;
986 Index<K,V> q = h;
987 Index<K,V> r = q.right;
988 Index<K,V> t = idx;
989 for (;;) {
990 if (r != null) {
991 Node<K,V> n = r.node;
992 // compare before deletion check avoids needing recheck
993 int c = key.compareTo(n.key);
994 if (n.value == null) {
995 if (!q.unlink(r))
996 break;
997 r = q.right;
998 continue;
999 }
1000 if (c > 0) {
1001 q = r;
1002 r = r.right;
1003 continue;
1004 }
1005 }
1006
1007 if (j == insertionLevel) {
1008 // Don't insert index if node already deleted
1009 if (t.indexesDeletedNode()) {
1010 findNode(key); // cleans up
1011 return;
1012 }
1013 if (!q.link(r, t))
1014 break; // restart
1015 if (--insertionLevel == 0) {
1016 // need final deletion check before return
1017 if (t.indexesDeletedNode())
1018 findNode(key);
1019 return;
1020 }
1021 }
1022
1023 if (--j >= insertionLevel && j < indexLevel)
1024 t = t.down;
1025 q = q.down;
1026 r = q.right;
1027 }
1028 }
1029 }
1030
1031 /* ---------------- Deletion -------------- */
1032
1033 /**
1034 * Main deletion method. Locates node, nulls value, appends a
1035 * deletion marker, unlinks predecessor, removes associated index
1036 * nodes, and possibly reduces head index level.
1037 *
1038 * Index nodes are cleared out simply by calling findPredecessor.
1039 * which unlinks indexes to deleted nodes found along path to key,
1040 * which will include the indexes to this node. This is done
1041 * unconditionally. We can't check beforehand whether there are
1042 * index nodes because it might be the case that some or all
1043 * indexes hadn't been inserted yet for this node during initial
1044 * search for it, and we'd like to ensure lack of garbage
1045 * retention, so must call to be sure.
1046 *
1047 * @param okey the key
1048 * @param value if non-null, the value that must be
1049 * associated with key
1050 * @return the node, or null if not found
1051 */
1052 final V doRemove(Object okey, Object value) {
1053 Comparable<? super K> key = comparable(okey);
1054 for (;;) {
1055 Node<K,V> b = findPredecessor(key);
1056 Node<K,V> n = b.next;
1057 for (;;) {
1058 if (n == null)
1059 return null;
1060 Node<K,V> f = n.next;
1061 if (n != b.next) // inconsistent read
1062 break;
1063 Object v = n.value;
1064 if (v == null) { // n is deleted
1065 n.helpDelete(b, f);
1066 break;
1067 }
1068 if (v == n || b.value == null) // b is deleted
1069 break;
1070 int c = key.compareTo(n.key);
1071 if (c < 0)
1072 return null;
1073 if (c > 0) {
1074 b = n;
1075 n = f;
1076 continue;
1077 }
1078 if (value != null && !value.equals(v))
1079 return null;
1080 if (!n.casValue(v, null))
1081 break;
1082 if (!n.appendMarker(f) || !b.casNext(n, f))
1083 findNode(key); // Retry via findNode
1084 else {
1085 findPredecessor(key); // Clean index
1086 if (head.right == null)
1087 tryReduceLevel();
1088 }
1089 return (V)v;
1090 }
1091 }
1092 }
1093
1094 /**
1095 * Possibly reduce head level if it has no nodes. This method can
1096 * (rarely) make mistakes, in which case levels can disappear even
1097 * though they are about to contain index nodes. This impacts
1098 * performance, not correctness. To minimize mistakes as well as
1099 * to reduce hysteresis, the level is reduced by one only if the
1100 * topmost three levels look empty. Also, if the removed level
1101 * looks non-empty after CAS, we try to change it back quick
1102 * before anyone notices our mistake! (This trick works pretty
1103 * well because this method will practically never make mistakes
1104 * unless current thread stalls immediately before first CAS, in
1105 * which case it is very unlikely to stall again immediately
1106 * afterwards, so will recover.)
1107 *
1108 * We put up with all this rather than just let levels grow
1109 * because otherwise, even a small map that has undergone a large
1110 * number of insertions and removals will have a lot of levels,
1111 * slowing down access more than would an occasional unwanted
1112 * reduction.
1113 */
1114 private void tryReduceLevel() {
1115 HeadIndex<K,V> h = head;
1116 HeadIndex<K,V> d;
1117 HeadIndex<K,V> e;
1118 if (h.level > 3 &&
1119 (d = (HeadIndex<K,V>)h.down) != null &&
1120 (e = (HeadIndex<K,V>)d.down) != null &&
1121 e.right == null &&
1122 d.right == null &&
1123 h.right == null &&
1124 casHead(h, d) && // try to set
1125 h.right != null) // recheck
1126 casHead(d, h); // try to backout
1127 }
1128
1129 /* ---------------- Finding and removing first element -------------- */
1130
1131 /**
1132 * Specialized variant of findNode to get first valid node.
1133 * @return first node or null if empty
1134 */
1135 Node<K,V> findFirst() {
1136 for (;;) {
1137 Node<K,V> b = head.node;
1138 Node<K,V> n = b.next;
1139 if (n == null)
1140 return null;
1141 if (n.value != null)
1142 return n;
1143 n.helpDelete(b, n.next);
1144 }
1145 }
1146
1147 /**
1148 * Removes first entry; returns its snapshot.
1149 * @return null if empty, else snapshot of first entry
1150 */
1151 Map.Entry<K,V> doRemoveFirstEntry() {
1152 for (;;) {
1153 Node<K,V> b = head.node;
1154 Node<K,V> n = b.next;
1155 if (n == null)
1156 return null;
1157 Node<K,V> f = n.next;
1158 if (n != b.next)
1159 continue;
1160 Object v = n.value;
1161 if (v == null) {
1162 n.helpDelete(b, f);
1163 continue;
1164 }
1165 if (!n.casValue(v, null))
1166 continue;
1167 if (!n.appendMarker(f) || !b.casNext(n, f))
1168 findFirst(); // retry
1169 clearIndexToFirst();
1170 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
1171 }
1172 }
1173
1174 /**
1175 * Clears out index nodes associated with deleted first entry.
1176 */
1177 private void clearIndexToFirst() {
1178 for (;;) {
1179 Index<K,V> q = head;
1180 for (;;) {
1181 Index<K,V> r = q.right;
1182 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1183 break;
1184 if ((q = q.down) == null) {
1185 if (head.right == null)
1186 tryReduceLevel();
1187 return;
1188 }
1189 }
1190 }
1191 }
1192
1193
1194 /* ---------------- Finding and removing last element -------------- */
1195
1196 /**
1197 * Specialized version of find to get last valid node.
1198 * @return last node or null if empty
1199 */
1200 Node<K,V> findLast() {
1201 /*
1202 * findPredecessor can't be used to traverse index level
1203 * because this doesn't use comparisons. So traversals of
1204 * both levels are folded together.
1205 */
1206 Index<K,V> q = head;
1207 for (;;) {
1208 Index<K,V> d, r;
1209 if ((r = q.right) != null) {
1210 if (r.indexesDeletedNode()) {
1211 q.unlink(r);
1212 q = head; // restart
1213 }
1214 else
1215 q = r;
1216 } else if ((d = q.down) != null) {
1217 q = d;
1218 } else {
1219 Node<K,V> b = q.node;
1220 Node<K,V> n = b.next;
1221 for (;;) {
1222 if (n == null)
1223 return b.isBaseHeader() ? null : b;
1224 Node<K,V> f = n.next; // inconsistent read
1225 if (n != b.next)
1226 break;
1227 Object v = n.value;
1228 if (v == null) { // n is deleted
1229 n.helpDelete(b, f);
1230 break;
1231 }
1232 if (v == n || b.value == null) // b is deleted
1233 break;
1234 b = n;
1235 n = f;
1236 }
1237 q = head; // restart
1238 }
1239 }
1240 }
1241
1242 /**
1243 * Specialized variant of findPredecessor to get predecessor of last
1244 * valid node. Needed when removing the last entry. It is possible
1245 * that all successors of returned node will have been deleted upon
1246 * return, in which case this method can be retried.
1247 * @return likely predecessor of last node
1248 */
1249 private Node<K,V> findPredecessorOfLast() {
1250 for (;;) {
1251 Index<K,V> q = head;
1252 for (;;) {
1253 Index<K,V> d, r;
1254 if ((r = q.right) != null) {
1255 if (r.indexesDeletedNode()) {
1256 q.unlink(r);
1257 break; // must restart
1258 }
1259 // proceed as far across as possible without overshooting
1260 if (r.node.next != null) {
1261 q = r;
1262 continue;
1263 }
1264 }
1265 if ((d = q.down) != null)
1266 q = d;
1267 else
1268 return q.node;
1269 }
1270 }
1271 }
1272
1273 /**
1274 * Removes last entry; returns its snapshot.
1275 * Specialized variant of doRemove.
1276 * @return null if empty, else snapshot of last entry
1277 */
1278 Map.Entry<K,V> doRemoveLastEntry() {
1279 for (;;) {
1280 Node<K,V> b = findPredecessorOfLast();
1281 Node<K,V> n = b.next;
1282 if (n == null) {
1283 if (b.isBaseHeader()) // empty
1284 return null;
1285 else
1286 continue; // all b's successors are deleted; retry
1287 }
1288 for (;;) {
1289 Node<K,V> f = n.next;
1290 if (n != b.next) // inconsistent read
1291 break;
1292 Object v = n.value;
1293 if (v == null) { // n is deleted
1294 n.helpDelete(b, f);
1295 break;
1296 }
1297 if (v == n || b.value == null) // b is deleted
1298 break;
1299 if (f != null) {
1300 b = n;
1301 n = f;
1302 continue;
1303 }
1304 if (!n.casValue(v, null))
1305 break;
1306 K key = n.key;
1307 Comparable<? super K> ck = comparable(key);
1308 if (!n.appendMarker(f) || !b.casNext(n, f))
1309 findNode(ck); // Retry via findNode
1310 else {
1311 findPredecessor(ck); // Clean index
1312 if (head.right == null)
1313 tryReduceLevel();
1314 }
1315 return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1316 }
1317 }
1318 }
1319
1320 /* ---------------- Relational operations -------------- */
1321
1322 // Control values OR'ed as arguments to findNear
1323
1324 private static final int EQ = 1;
1325 private static final int LT = 2;
1326 private static final int GT = 0; // Actually checked as !LT
1327
1328 /**
1329 * Utility for ceiling, floor, lower, higher methods.
1330 * @param kkey the key
1331 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1332 * @return nearest node fitting relation, or null if no such
1333 */
1334 Node<K,V> findNear(K kkey, int rel) {
1335 Comparable<? super K> key = comparable(kkey);
1336 for (;;) {
1337 Node<K,V> b = findPredecessor(key);
1338 Node<K,V> n = b.next;
1339 for (;;) {
1340 if (n == null)
1341 return ((rel & LT) == 0 || b.isBaseHeader()) ? null : b;
1342 Node<K,V> f = n.next;
1343 if (n != b.next) // inconsistent read
1344 break;
1345 Object v = n.value;
1346 if (v == null) { // n is deleted
1347 n.helpDelete(b, f);
1348 break;
1349 }
1350 if (v == n || b.value == null) // b is deleted
1351 break;
1352 int c = key.compareTo(n.key);
1353 if ((c == 0 && (rel & EQ) != 0) ||
1354 (c < 0 && (rel & LT) == 0))
1355 return n;
1356 if ( c <= 0 && (rel & LT) != 0)
1357 return b.isBaseHeader() ? null : b;
1358 b = n;
1359 n = f;
1360 }
1361 }
1362 }
1363
1364 /**
1365 * Returns SimpleImmutableEntry for results of findNear.
1366 * @param key the key
1367 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1368 * @return Entry fitting relation, or null if no such
1369 */
1370 AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
1371 for (;;) {
1372 Node<K,V> n = findNear(key, rel);
1373 if (n == null)
1374 return null;
1375 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1376 if (e != null)
1377 return e;
1378 }
1379 }
1380
1381
1382 /* ---------------- Constructors -------------- */
1383
1384 /**
1385 * Constructs a new, empty map, sorted according to the
1386 * {@linkplain Comparable natural ordering} of the keys.
1387 */
1388 public ConcurrentSkipListMap() {
1389 this.comparator = null;
1390 initialize();
1391 }
1392
1393 /**
1394 * Constructs a new, empty map, sorted according to the specified
1395 * comparator.
1396 *
1397 * @param comparator the comparator that will be used to order this map.
1398 * If <tt>null</tt>, the {@linkplain Comparable natural
1399 * ordering} of the keys will be used.
1400 */
1401 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1402 this.comparator = comparator;
1403 initialize();
1404 }
1405
1406 /**
1407 * Constructs a new map containing the same mappings as the given map,
1408 * sorted according to the {@linkplain Comparable natural ordering} of
1409 * the keys.
1410 *
1411 * @param m the map whose mappings are to be placed in this map
1412 * @throws ClassCastException if the keys in <tt>m</tt> are not
1413 * {@link Comparable}, or are not mutually comparable
1414 * @throws NullPointerException if the specified map or any of its keys
1415 * or values are null
1416 */
1417 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1418 this.comparator = null;
1419 initialize();
1420 putAll(m);
1421 }
1422
1423 /**
1424 * Constructs a new map containing the same mappings and using the
1425 * same ordering as the specified sorted map.
1426 *
1427 * @param m the sorted map whose mappings are to be placed in this
1428 * map, and whose comparator is to be used to sort this map
1429 * @throws NullPointerException if the specified sorted map or any of
1430 * its keys or values are null
1431 */
1432 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1433 this.comparator = m.comparator();
1434 initialize();
1435 buildFromSorted(m);
1436 }
1437
1438 /**
1439 * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
1440 * instance. (The keys and values themselves are not cloned.)
1441 *
1442 * @return a shallow copy of this map
1443 */
1444 public ConcurrentSkipListMap<K,V> clone() {
1445 ConcurrentSkipListMap<K,V> clone = null;
1446 try {
1447 clone = (ConcurrentSkipListMap<K,V>) super.clone();
1448 } catch (CloneNotSupportedException e) {
1449 throw new InternalError();
1450 }
1451
1452 clone.initialize();
1453 clone.buildFromSorted(this);
1454 return clone;
1455 }
1456
1457 /**
1458 * Streamlined bulk insertion to initialize from elements of
1459 * given sorted map. Call only from constructor or clone
1460 * method.
1461 */
1462 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1463 if (map == null)
1464 throw new NullPointerException();
1465
1466 HeadIndex<K,V> h = head;
1467 Node<K,V> basepred = h.node;
1468
1469 // Track the current rightmost node at each level. Uses an
1470 // ArrayList to avoid committing to initial or maximum level.
1471 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1472
1473 // initialize
1474 for (int i = 0; i <= h.level; ++i)
1475 preds.add(null);
1476 Index<K,V> q = h;
1477 for (int i = h.level; i > 0; --i) {
1478 preds.set(i, q);
1479 q = q.down;
1480 }
1481
1482 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1483 map.entrySet().iterator();
1484 while (it.hasNext()) {
1485 Map.Entry<? extends K, ? extends V> e = it.next();
1486 int j = randomLevel();
1487 if (j > h.level) j = h.level + 1;
1488 K k = e.getKey();
1489 V v = e.getValue();
1490 if (k == null || v == null)
1491 throw new NullPointerException();
1492 Node<K,V> z = new Node<K,V>(k, v, null);
1493 basepred.next = z;
1494 basepred = z;
1495 if (j > 0) {
1496 Index<K,V> idx = null;
1497 for (int i = 1; i <= j; ++i) {
1498 idx = new Index<K,V>(z, idx, null);
1499 if (i > h.level)
1500 h = new HeadIndex<K,V>(h.node, h, idx, i);
1501
1502 if (i < preds.size()) {
1503 preds.get(i).right = idx;
1504 preds.set(i, idx);
1505 } else
1506 preds.add(idx);
1507 }
1508 }
1509 }
1510 head = h;
1511 }
1512
1513 /* ---------------- Serialization -------------- */
1514
1515 /**
1516 * Save the state of this map to a stream.
1517 *
1518 * @serialData The key (Object) and value (Object) for each
1519 * key-value mapping represented by the map, followed by
1520 * <tt>null</tt>. The key-value mappings are emitted in key-order
1521 * (as determined by the Comparator, or by the keys' natural
1522 * ordering if no Comparator).
1523 */
1524 private void writeObject(java.io.ObjectOutputStream s)
1525 throws java.io.IOException {
1526 // Write out the Comparator and any hidden stuff
1527 s.defaultWriteObject();
1528
1529 // Write out keys and values (alternating)
1530 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1531 V v = n.getValidValue();
1532 if (v != null) {
1533 s.writeObject(n.key);
1534 s.writeObject(v);
1535 }
1536 }
1537 s.writeObject(null);
1538 }
1539
1540 /**
1541 * Reconstitute the map from a stream.
1542 */
1543 private void readObject(final java.io.ObjectInputStream s)
1544 throws java.io.IOException, ClassNotFoundException {
1545 // Read in the Comparator and any hidden stuff
1546 s.defaultReadObject();
1547 // Reset transients
1548 initialize();
1549
1550 /*
1551 * This is nearly identical to buildFromSorted, but is
1552 * distinct because readObject calls can't be nicely adapted
1553 * as the kind of iterator needed by buildFromSorted. (They
1554 * can be, but doing so requires type cheats and/or creation
1555 * of adaptor classes.) It is simpler to just adapt the code.
1556 */
1557
1558 HeadIndex<K,V> h = head;
1559 Node<K,V> basepred = h.node;
1560 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1561 for (int i = 0; i <= h.level; ++i)
1562 preds.add(null);
1563 Index<K,V> q = h;
1564 for (int i = h.level; i > 0; --i) {
1565 preds.set(i, q);
1566 q = q.down;
1567 }
1568
1569 for (;;) {
1570 Object k = s.readObject();
1571 if (k == null)
1572 break;
1573 Object v = s.readObject();
1574 if (v == null)
1575 throw new NullPointerException();
1576 K key = (K) k;
1577 V val = (V) v;
1578 int j = randomLevel();
1579 if (j > h.level) j = h.level + 1;
1580 Node<K,V> z = new Node<K,V>(key, val, null);
1581 basepred.next = z;
1582 basepred = z;
1583 if (j > 0) {
1584 Index<K,V> idx = null;
1585 for (int i = 1; i <= j; ++i) {
1586 idx = new Index<K,V>(z, idx, null);
1587 if (i > h.level)
1588 h = new HeadIndex<K,V>(h.node, h, idx, i);
1589
1590 if (i < preds.size()) {
1591 preds.get(i).right = idx;
1592 preds.set(i, idx);
1593 } else
1594 preds.add(idx);
1595 }
1596 }
1597 }
1598 head = h;
1599 }
1600
1601 /* ------ Map API methods ------ */
1602
1603 /**
1604 * Returns <tt>true</tt> if this map contains a mapping for the specified
1605 * key.
1606 *
1607 * @param key key whose presence in this map is to be tested
1608 * @return <tt>true</tt> if this map contains a mapping for the specified key
1609 * @throws ClassCastException if the specified key cannot be compared
1610 * with the keys currently in the map
1611 * @throws NullPointerException if the specified key is null
1612 */
1613 public boolean containsKey(Object key) {
1614 return doGet(key) != null;
1615 }
1616
1617 /**
1618 * Returns the value to which the specified key is mapped,
1619 * or {@code null} if this map contains no mapping for the key.
1620 *
1621 * <p>More formally, if this map contains a mapping from a key
1622 * {@code k} to a value {@code v} such that {@code key} compares
1623 * equal to {@code k} according to the map's ordering, then this
1624 * method returns {@code v}; otherwise it returns {@code null}.
1625 * (There can be at most one such mapping.)
1626 *
1627 * @throws ClassCastException if the specified key cannot be compared
1628 * with the keys currently in the map
1629 * @throws NullPointerException if the specified key is null
1630 */
1631 public V get(Object key) {
1632 return doGet(key);
1633 }
1634
1635 /**
1636 * Associates the specified value with the specified key in this map.
1637 * If the map previously contained a mapping for the key, the old
1638 * value is replaced.
1639 *
1640 * @param key key with which the specified value is to be associated
1641 * @param value value to be associated with the specified key
1642 * @return the previous value associated with the specified key, or
1643 * <tt>null</tt> if there was no mapping for the key
1644 * @throws ClassCastException if the specified key cannot be compared
1645 * with the keys currently in the map
1646 * @throws NullPointerException if the specified key or value is null
1647 */
1648 public V put(K key, V value) {
1649 if (value == null)
1650 throw new NullPointerException();
1651 return doPut(key, value, false);
1652 }
1653
1654 /**
1655 * Removes the mapping for the specified key from this map if present.
1656 *
1657 * @param key key for which mapping should be removed
1658 * @return the previous value associated with the specified key, or
1659 * <tt>null</tt> if there was no mapping for the key
1660 * @throws ClassCastException if the specified key cannot be compared
1661 * with the keys currently in the map
1662 * @throws NullPointerException if the specified key is null
1663 */
1664 public V remove(Object key) {
1665 return doRemove(key, null);
1666 }
1667
1668 /**
1669 * Returns <tt>true</tt> if this map maps one or more keys to the
1670 * specified value. This operation requires time linear in the
1671 * map size.
1672 *
1673 * @param value value whose presence in this map is to be tested
1674 * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1675 * <tt>false</tt> otherwise
1676 * @throws NullPointerException if the specified value is null
1677 */
1678 public boolean containsValue(Object value) {
1679 if (value == null)
1680 throw new NullPointerException();
1681 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1682 V v = n.getValidValue();
1683 if (v != null && value.equals(v))
1684 return true;
1685 }
1686 return false;
1687 }
1688
1689 /**
1690 * Returns the number of key-value mappings in this map. If this map
1691 * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1692 * returns <tt>Integer.MAX_VALUE</tt>.
1693 *
1694 * <p>Beware that, unlike in most collections, this method is
1695 * <em>NOT</em> a constant-time operation. Because of the
1696 * asynchronous nature of these maps, determining the current
1697 * number of elements requires traversing them all to count them.
1698 * Additionally, it is possible for the size to change during
1699 * execution of this method, in which case the returned result
1700 * will be inaccurate. Thus, this method is typically not very
1701 * useful in concurrent applications.
1702 *
1703 * @return the number of elements in this map
1704 */
1705 public int size() {
1706 long count = 0;
1707 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1708 if (n.getValidValue() != null)
1709 ++count;
1710 }
1711 return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count;
1712 }
1713
1714 /**
1715 * Returns <tt>true</tt> if this map contains no key-value mappings.
1716 * @return <tt>true</tt> if this map contains no key-value mappings
1717 */
1718 public boolean isEmpty() {
1719 return findFirst() == null;
1720 }
1721
1722 /**
1723 * Removes all of the mappings from this map.
1724 */
1725 public void clear() {
1726 initialize();
1727 }
1728
1729 /* ---------------- View methods -------------- */
1730
1731 /*
1732 * Note: Lazy initialization works for views because view classes
1733 * are stateless/immutable so it doesn't matter wrt correctness if
1734 * more than one is created (which will only rarely happen). Even
1735 * so, the following idiom conservatively ensures that the method
1736 * returns the one it created if it does so, not one created by
1737 * another racing thread.
1738 */
1739
1740 /**
1741 * Returns a {@link NavigableSet} view of the keys contained in this map.
1742 * The set's iterator returns the keys in ascending order.
1743 * The set is backed by the map, so changes to the map are
1744 * reflected in the set, and vice-versa. The set supports element
1745 * removal, which removes the corresponding mapping from the map,
1746 * via the {@code Iterator.remove}, {@code Set.remove},
1747 * {@code removeAll}, {@code retainAll}, and {@code clear}
1748 * operations. It does not support the {@code add} or {@code addAll}
1749 * operations.
1750 *
1751 * <p>The view's {@code iterator} is a "weakly consistent" iterator
1752 * that will never throw {@link ConcurrentModificationException},
1753 * and guarantees to traverse elements as they existed upon
1754 * construction of the iterator, and may (but is not guaranteed to)
1755 * reflect any modifications subsequent to construction.
1756 *
1757 * <p>This method is equivalent to method {@code navigableKeySet}.
1758 *
1759 * @return a navigable set view of the keys in this map
1760 */
1761 public NavigableSet<K> keySet() {
1762 KeySet ks = keySet;
1763 return (ks != null) ? ks : (keySet = new KeySet(this));
1764 }
1765
1766 public NavigableSet<K> navigableKeySet() {
1767 KeySet ks = keySet;
1768 return (ks != null) ? ks : (keySet = new KeySet(this));
1769 }
1770
1771 /**
1772 * Returns a {@link Collection} view of the values contained in this map.
1773 * The collection's iterator returns the values in ascending order
1774 * of the corresponding keys.
1775 * The collection is backed by the map, so changes to the map are
1776 * reflected in the collection, and vice-versa. The collection
1777 * supports element removal, which removes the corresponding
1778 * mapping from the map, via the <tt>Iterator.remove</tt>,
1779 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1780 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1781 * support the <tt>add</tt> or <tt>addAll</tt> operations.
1782 *
1783 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1784 * that will never throw {@link ConcurrentModificationException},
1785 * and guarantees to traverse elements as they existed upon
1786 * construction of the iterator, and may (but is not guaranteed to)
1787 * reflect any modifications subsequent to construction.
1788 */
1789 public Collection<V> values() {
1790 Values vs = values;
1791 return (vs != null) ? vs : (values = new Values(this));
1792 }
1793
1794 /**
1795 * Returns a {@link Set} view of the mappings contained in this map.
1796 * The set's iterator returns the entries in ascending key order.
1797 * The set is backed by the map, so changes to the map are
1798 * reflected in the set, and vice-versa. The set supports element
1799 * removal, which removes the corresponding mapping from the map,
1800 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1801 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1802 * operations. It does not support the <tt>add</tt> or
1803 * <tt>addAll</tt> operations.
1804 *
1805 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1806 * that will never throw {@link ConcurrentModificationException},
1807 * and guarantees to traverse elements as they existed upon
1808 * construction of the iterator, and may (but is not guaranteed to)
1809 * reflect any modifications subsequent to construction.
1810 *
1811 * <p>The <tt>Map.Entry</tt> elements returned by
1812 * <tt>iterator.next()</tt> do <em>not</em> support the
1813 * <tt>setValue</tt> operation.
1814 *
1815 * @return a set view of the mappings contained in this map,
1816 * sorted in ascending key order
1817 */
1818 public Set<Map.Entry<K,V>> entrySet() {
1819 EntrySet es = entrySet;
1820 return (es != null) ? es : (entrySet = new EntrySet(this));
1821 }
1822
1823 public ConcurrentNavigableMap<K,V> descendingMap() {
1824 ConcurrentNavigableMap<K,V> dm = descendingMap;
1825 return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
1826 (this, null, false, null, false, true));
1827 }
1828
1829 public NavigableSet<K> descendingKeySet() {
1830 return descendingMap().navigableKeySet();
1831 }
1832
1833 /* ---------------- AbstractMap Overrides -------------- */
1834
1835 /**
1836 * Compares the specified object with this map for equality.
1837 * Returns <tt>true</tt> if the given object is also a map and the
1838 * two maps represent the same mappings. More formally, two maps
1839 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
1840 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This
1841 * operation may return misleading results if either map is
1842 * concurrently modified during execution of this method.
1843 *
1844 * @param o object to be compared for equality with this map
1845 * @return <tt>true</tt> if the specified object is equal to this map
1846 */
1847 public boolean equals(Object o) {
1848 if (o == this)
1849 return true;
1850 if (!(o instanceof Map))
1851 return false;
1852 Map<?,?> m = (Map<?,?>) o;
1853 try {
1854 for (Map.Entry<K,V> e : this.entrySet())
1855 if (! e.getValue().equals(m.get(e.getKey())))
1856 return false;
1857 for (Map.Entry<?,?> e : m.entrySet()) {
1858 Object k = e.getKey();
1859 Object v = e.getValue();
1860 if (k == null || v == null || !v.equals(get(k)))
1861 return false;
1862 }
1863 return true;
1864 } catch (ClassCastException unused) {
1865 return false;
1866 } catch (NullPointerException unused) {
1867 return false;
1868 }
1869 }
1870
1871 /* ------ ConcurrentMap API methods ------ */
1872
1873 /**
1874 * {@inheritDoc}
1875 *
1876 * @return the previous value associated with the specified key,
1877 * or <tt>null</tt> if there was no mapping for the key
1878 * @throws ClassCastException if the specified key cannot be compared
1879 * with the keys currently in the map
1880 * @throws NullPointerException if the specified key or value is null
1881 */
1882 public V putIfAbsent(K key, V value) {
1883 if (value == null)
1884 throw new NullPointerException();
1885 return doPut(key, value, true);
1886 }
1887
1888 /**
1889 * {@inheritDoc}
1890 *
1891 * @throws ClassCastException if the specified key cannot be compared
1892 * with the keys currently in the map
1893 * @throws NullPointerException if the specified key is null
1894 */
1895 public boolean remove(Object key, Object value) {
1896 if (key == null)
1897 throw new NullPointerException();
1898 if (value == null)
1899 return false;
1900 return doRemove(key, value) != null;
1901 }
1902
1903 /**
1904 * {@inheritDoc}
1905 *
1906 * @throws ClassCastException if the specified key cannot be compared
1907 * with the keys currently in the map
1908 * @throws NullPointerException if any of the arguments are null
1909 */
1910 public boolean replace(K key, V oldValue, V newValue) {
1911 if (oldValue == null || newValue == null)
1912 throw new NullPointerException();
1913 Comparable<? super K> k = comparable(key);
1914 for (;;) {
1915 Node<K,V> n = findNode(k);
1916 if (n == null)
1917 return false;
1918 Object v = n.value;
1919 if (v != null) {
1920 if (!oldValue.equals(v))
1921 return false;
1922 if (n.casValue(v, newValue))
1923 return true;
1924 }
1925 }
1926 }
1927
1928 /**
1929 * {@inheritDoc}
1930 *
1931 * @return the previous value associated with the specified key,
1932 * or <tt>null</tt> if there was no mapping for the key
1933 * @throws ClassCastException if the specified key cannot be compared
1934 * with the keys currently in the map
1935 * @throws NullPointerException if the specified key or value is null
1936 */
1937 public V replace(K key, V value) {
1938 if (value == null)
1939 throw new NullPointerException();
1940 Comparable<? super K> k = comparable(key);
1941 for (;;) {
1942 Node<K,V> n = findNode(k);
1943 if (n == null)
1944 return null;
1945 Object v = n.value;
1946 if (v != null && n.casValue(v, value))
1947 return (V)v;
1948 }
1949 }
1950
1951 /* ------ SortedMap API methods ------ */
1952
1953 public Comparator<? super K> comparator() {
1954 return comparator;
1955 }
1956
1957 /**
1958 * @throws NoSuchElementException {@inheritDoc}
1959 */
1960 public K firstKey() {
1961 Node<K,V> n = findFirst();
1962 if (n == null)
1963 throw new NoSuchElementException();
1964 return n.key;
1965 }
1966
1967 /**
1968 * @throws NoSuchElementException {@inheritDoc}
1969 */
1970 public K lastKey() {
1971 Node<K,V> n = findLast();
1972 if (n == null)
1973 throw new NoSuchElementException();
1974 return n.key;
1975 }
1976
1977 /**
1978 * @throws ClassCastException {@inheritDoc}
1979 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1980 * @throws IllegalArgumentException {@inheritDoc}
1981 */
1982 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
1983 boolean fromInclusive,
1984 K toKey,
1985 boolean toInclusive) {
1986 if (fromKey == null || toKey == null)
1987 throw new NullPointerException();
1988 return new SubMap<K,V>
1989 (this, fromKey, fromInclusive, toKey, toInclusive, false);
1990 }
1991
1992 /**
1993 * @throws ClassCastException {@inheritDoc}
1994 * @throws NullPointerException if {@code toKey} is null
1995 * @throws IllegalArgumentException {@inheritDoc}
1996 */
1997 public ConcurrentNavigableMap<K,V> headMap(K toKey,
1998 boolean inclusive) {
1999 if (toKey == null)
2000 throw new NullPointerException();
2001 return new SubMap<K,V>
2002 (this, null, false, toKey, inclusive, false);
2003 }
2004
2005 /**
2006 * @throws ClassCastException {@inheritDoc}
2007 * @throws NullPointerException if {@code fromKey} is null
2008 * @throws IllegalArgumentException {@inheritDoc}
2009 */
2010 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2011 boolean inclusive) {
2012 if (fromKey == null)
2013 throw new NullPointerException();
2014 return new SubMap<K,V>
2015 (this, fromKey, inclusive, null, false, false);
2016 }
2017
2018 /**
2019 * @throws ClassCastException {@inheritDoc}
2020 * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2021 * @throws IllegalArgumentException {@inheritDoc}
2022 */
2023 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2024 return subMap(fromKey, true, toKey, false);
2025 }
2026
2027 /**
2028 * @throws ClassCastException {@inheritDoc}
2029 * @throws NullPointerException if {@code toKey} is null
2030 * @throws IllegalArgumentException {@inheritDoc}
2031 */
2032 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2033 return headMap(toKey, false);
2034 }
2035
2036 /**
2037 * @throws ClassCastException {@inheritDoc}
2038 * @throws NullPointerException if {@code fromKey} is null
2039 * @throws IllegalArgumentException {@inheritDoc}
2040 */
2041 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2042 return tailMap(fromKey, true);
2043 }
2044
2045 /* ---------------- Relational operations -------------- */
2046
2047 /**
2048 * Returns a key-value mapping associated with the greatest key
2049 * strictly less than the given key, or <tt>null</tt> if there is
2050 * no such key. The returned entry does <em>not</em> support the
2051 * <tt>Entry.setValue</tt> method.
2052 *
2053 * @throws ClassCastException {@inheritDoc}
2054 * @throws NullPointerException if the specified key is null
2055 */
2056 public Map.Entry<K,V> lowerEntry(K key) {
2057 return getNear(key, LT);
2058 }
2059
2060 /**
2061 * @throws ClassCastException {@inheritDoc}
2062 * @throws NullPointerException if the specified key is null
2063 */
2064 public K lowerKey(K key) {
2065 Node<K,V> n = findNear(key, LT);
2066 return (n == null) ? null : n.key;
2067 }
2068
2069 /**
2070 * Returns a key-value mapping associated with the greatest key
2071 * less than or equal to the given key, or <tt>null</tt> if there
2072 * is no such key. The returned entry does <em>not</em> support
2073 * the <tt>Entry.setValue</tt> method.
2074 *
2075 * @param key the key
2076 * @throws ClassCastException {@inheritDoc}
2077 * @throws NullPointerException if the specified key is null
2078 */
2079 public Map.Entry<K,V> floorEntry(K key) {
2080 return getNear(key, LT|EQ);
2081 }
2082
2083 /**
2084 * @param key the key
2085 * @throws ClassCastException {@inheritDoc}
2086 * @throws NullPointerException if the specified key is null
2087 */
2088 public K floorKey(K key) {
2089 Node<K,V> n = findNear(key, LT|EQ);
2090 return (n == null) ? null : n.key;
2091 }
2092
2093 /**
2094 * Returns a key-value mapping associated with the least key
2095 * greater than or equal to the given key, or <tt>null</tt> if
2096 * there is no such entry. The returned entry does <em>not</em>
2097 * support the <tt>Entry.setValue</tt> method.
2098 *
2099 * @throws ClassCastException {@inheritDoc}
2100 * @throws NullPointerException if the specified key is null
2101 */
2102 public Map.Entry<K,V> ceilingEntry(K key) {
2103 return getNear(key, GT|EQ);
2104 }
2105
2106 /**
2107 * @throws ClassCastException {@inheritDoc}
2108 * @throws NullPointerException if the specified key is null
2109 */
2110 public K ceilingKey(K key) {
2111 Node<K,V> n = findNear(key, GT|EQ);
2112 return (n == null) ? null : n.key;
2113 }
2114
2115 /**
2116 * Returns a key-value mapping associated with the least key
2117 * strictly greater than the given key, or <tt>null</tt> if there
2118 * is no such key. The returned entry does <em>not</em> support
2119 * the <tt>Entry.setValue</tt> method.
2120 *
2121 * @param key the key
2122 * @throws ClassCastException {@inheritDoc}
2123 * @throws NullPointerException if the specified key is null
2124 */
2125 public Map.Entry<K,V> higherEntry(K key) {
2126 return getNear(key, GT);
2127 }
2128
2129 /**
2130 * @param key the key
2131 * @throws ClassCastException {@inheritDoc}
2132 * @throws NullPointerException if the specified key is null
2133 */
2134 public K higherKey(K key) {
2135 Node<K,V> n = findNear(key, GT);
2136 return (n == null) ? null : n.key;
2137 }
2138
2139 /**
2140 * Returns a key-value mapping associated with the least
2141 * key in this map, or <tt>null</tt> if the map is empty.
2142 * The returned entry does <em>not</em> support
2143 * the <tt>Entry.setValue</tt> method.
2144 */
2145 public Map.Entry<K,V> firstEntry() {
2146 for (;;) {
2147 Node<K,V> n = findFirst();
2148 if (n == null)
2149 return null;
2150 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2151 if (e != null)
2152 return e;
2153 }
2154 }
2155
2156 /**
2157 * Returns a key-value mapping associated with the greatest
2158 * key in this map, or <tt>null</tt> if the map is empty.
2159 * The returned entry does <em>not</em> support
2160 * the <tt>Entry.setValue</tt> method.
2161 */
2162 public Map.Entry<K,V> lastEntry() {
2163 for (;;) {
2164 Node<K,V> n = findLast();
2165 if (n == null)
2166 return null;
2167 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2168 if (e != null)
2169 return e;
2170 }
2171 }
2172
2173 /**
2174 * Removes and returns a key-value mapping associated with
2175 * the least key in this map, or <tt>null</tt> if the map is empty.
2176 * The returned entry does <em>not</em> support
2177 * the <tt>Entry.setValue</tt> method.
2178 */
2179 public Map.Entry<K,V> pollFirstEntry() {
2180 return doRemoveFirstEntry();
2181 }
2182
2183 /**
2184 * Removes and returns a key-value mapping associated with
2185 * the greatest key in this map, or <tt>null</tt> if the map is empty.
2186 * The returned entry does <em>not</em> support
2187 * the <tt>Entry.setValue</tt> method.
2188 */
2189 public Map.Entry<K,V> pollLastEntry() {
2190 return doRemoveLastEntry();
2191 }
2192
2193
2194 /* ---------------- Iterators -------------- */
2195
2196 /**
2197 * Base of iterator classes:
2198 */
2199 abstract class Iter<T> implements Iterator<T> {
2200 /** the last node returned by next() */
2201 Node<K,V> lastReturned;
2202 /** the next node to return from next(); */
2203 Node<K,V> next;
2204 /** Cache of next value field to maintain weak consistency */
2205 V nextValue;
2206
2207 /** Initializes ascending iterator for entire range. */
2208 Iter() {
2209 for (;;) {
2210 next = findFirst();
2211 if (next == null)
2212 break;
2213 Object x = next.value;
2214 if (x != null && x != next) {
2215 nextValue = (V) x;
2216 break;
2217 }
2218 }
2219 }
2220
2221 public final boolean hasNext() {
2222 return next != null;
2223 }
2224
2225 /** Advances next to higher entry. */
2226 final void advance() {
2227 if (next == null)
2228 throw new NoSuchElementException();
2229 lastReturned = next;
2230 for (;;) {
2231 next = next.next;
2232 if (next == null)
2233 break;
2234 Object x = next.value;
2235 if (x != null && x != next) {
2236 nextValue = (V) x;
2237 break;
2238 }
2239 }
2240 }
2241
2242 public void remove() {
2243 Node<K,V> l = lastReturned;
2244 if (l == null)
2245 throw new IllegalStateException();
2246 // It would not be worth all of the overhead to directly
2247 // unlink from here. Using remove is fast enough.
2248 ConcurrentSkipListMap.this.remove(l.key);
2249 lastReturned = null;
2250 }
2251
2252 }
2253
2254 final class ValueIterator extends Iter<V> {
2255 public V next() {
2256 V v = nextValue;
2257 advance();
2258 return v;
2259 }
2260 }
2261
2262 final class KeyIterator extends Iter<K> {
2263 public K next() {
2264 Node<K,V> n = next;
2265 advance();
2266 return n.key;
2267 }
2268 }
2269
2270 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2271 public Map.Entry<K,V> next() {
2272 Node<K,V> n = next;
2273 V v = nextValue;
2274 advance();
2275 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2276 }
2277 }
2278
2279 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2280
2281 Iterator<K> keyIterator() {
2282 return new KeyIterator();
2283 }
2284
2285 Iterator<V> valueIterator() {
2286 return new ValueIterator();
2287 }
2288
2289 Iterator<Map.Entry<K,V>> entryIterator() {
2290 return new EntryIterator();
2291 }
2292
2293 /* ---------------- View Classes -------------- */
2294
2295 /*
2296 * View classes are static, delegating to a ConcurrentNavigableMap
2297 * to allow use by SubMaps, which outweighs the ugliness of
2298 * needing type-tests for Iterator methods.
2299 */
2300
2301 static final <E> List<E> toList(Collection<E> c) {
2302 // Using size() here would be a pessimization.
2303 List<E> list = new ArrayList<E>();
2304 for (E e : c)
2305 list.add(e);
2306 return list;
2307 }
2308
2309 static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
2310 private final ConcurrentNavigableMap<E,Object> m;
2311 KeySet(ConcurrentNavigableMap<E,Object> map) { m = map; }
2312 public int size() { return m.size(); }
2313 public boolean isEmpty() { return m.isEmpty(); }
2314 public boolean contains(Object o) { return m.containsKey(o); }
2315 public boolean remove(Object o) { return m.remove(o) != null; }
2316 public void clear() { m.clear(); }
2317 public E lower(E e) { return m.lowerKey(e); }
2318 public E floor(E e) { return m.floorKey(e); }
2319 public E ceiling(E e) { return m.ceilingKey(e); }
2320 public E higher(E e) { return m.higherKey(e); }
2321 public Comparator<? super E> comparator() { return m.comparator(); }
2322 public E first() { return m.firstKey(); }
2323 public E last() { return m.lastKey(); }
2324 public E pollFirst() {
2325 Map.Entry<E,Object> e = m.pollFirstEntry();
2326 return (e == null) ? null : e.getKey();
2327 }
2328 public E pollLast() {
2329 Map.Entry<E,Object> e = m.pollLastEntry();
2330 return (e == null) ? null : e.getKey();
2331 }
2332 public Iterator<E> iterator() {
2333 if (m instanceof ConcurrentSkipListMap)
2334 return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2335 else
2336 return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2337 }
2338 public boolean equals(Object o) {
2339 if (o == this)
2340 return true;
2341 if (!(o instanceof Set))
2342 return false;
2343 Collection<?> c = (Collection<?>) o;
2344 try {
2345 return containsAll(c) && c.containsAll(this);
2346 } catch (ClassCastException unused) {
2347 return false;
2348 } catch (NullPointerException unused) {
2349 return false;
2350 }
2351 }
2352 public Object[] toArray() { return toList(this).toArray(); }
2353 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2354 public Iterator<E> descendingIterator() {
2355 return descendingSet().iterator();
2356 }
2357 public NavigableSet<E> subSet(E fromElement,
2358 boolean fromInclusive,
2359 E toElement,
2360 boolean toInclusive) {
2361 return new KeySet<E>(m.subMap(fromElement, fromInclusive,
2362 toElement, toInclusive));
2363 }
2364 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2365 return new KeySet<E>(m.headMap(toElement, inclusive));
2366 }
2367 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2368 return new KeySet<E>(m.tailMap(fromElement, inclusive));
2369 }
2370 public NavigableSet<E> subSet(E fromElement, E toElement) {
2371 return subSet(fromElement, true, toElement, false);
2372 }
2373 public NavigableSet<E> headSet(E toElement) {
2374 return headSet(toElement, false);
2375 }
2376 public NavigableSet<E> tailSet(E fromElement) {
2377 return tailSet(fromElement, true);
2378 }
2379 public NavigableSet<E> descendingSet() {
2380 return new KeySet(m.descendingMap());
2381 }
2382 }
2383
2384 static final class Values<E> extends AbstractCollection<E> {
2385 private final ConcurrentNavigableMap<Object, E> m;
2386 Values(ConcurrentNavigableMap<Object, E> map) {
2387 m = map;
2388 }
2389 public Iterator<E> iterator() {
2390 if (m instanceof ConcurrentSkipListMap)
2391 return ((ConcurrentSkipListMap<Object,E>)m).valueIterator();
2392 else
2393 return ((SubMap<Object,E>)m).valueIterator();
2394 }
2395 public boolean isEmpty() {
2396 return m.isEmpty();
2397 }
2398 public int size() {
2399 return m.size();
2400 }
2401 public boolean contains(Object o) {
2402 return m.containsValue(o);
2403 }
2404 public void clear() {
2405 m.clear();
2406 }
2407 public Object[] toArray() { return toList(this).toArray(); }
2408 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2409 }
2410
2411 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2412 private final ConcurrentNavigableMap<K1, V1> m;
2413 EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2414 m = map;
2415 }
2416
2417 public Iterator<Map.Entry<K1,V1>> iterator() {
2418 if (m instanceof ConcurrentSkipListMap)
2419 return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2420 else
2421 return ((SubMap<K1,V1>)m).entryIterator();
2422 }
2423
2424 public boolean contains(Object o) {
2425 if (!(o instanceof Map.Entry))
2426 return false;
2427 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2428 V1 v = m.get(e.getKey());
2429 return v != null && v.equals(e.getValue());
2430 }
2431 public boolean remove(Object o) {
2432 if (!(o instanceof Map.Entry))
2433 return false;
2434 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2435 return m.remove(e.getKey(),
2436 e.getValue());
2437 }
2438 public boolean isEmpty() {
2439 return m.isEmpty();
2440 }
2441 public int size() {
2442 return m.size();
2443 }
2444 public void clear() {
2445 m.clear();
2446 }
2447 public boolean equals(Object o) {
2448 if (o == this)
2449 return true;
2450 if (!(o instanceof Set))
2451 return false;
2452 Collection<?> c = (Collection<?>) o;
2453 try {
2454 return containsAll(c) && c.containsAll(this);
2455 } catch (ClassCastException unused) {
2456 return false;
2457 } catch (NullPointerException unused) {
2458 return false;
2459 }
2460 }
2461 public Object[] toArray() { return toList(this).toArray(); }
2462 public <T> T[] toArray(T[] a) { return toList(this).toArray(a); }
2463 }
2464
2465 /**
2466 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2467 * represent a subrange of mappings of their underlying
2468 * maps. Instances of this class support all methods of their
2469 * underlying maps, differing in that mappings outside their range are
2470 * ignored, and attempts to add mappings outside their ranges result
2471 * in {@link IllegalArgumentException}. Instances of this class are
2472 * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2473 * <tt>tailMap</tt> methods of their underlying maps.
2474 *
2475 * @serial include
2476 */
2477 static final class SubMap<K,V> extends AbstractMap<K,V>
2478 implements ConcurrentNavigableMap<K,V>, Cloneable,
2479 java.io.Serializable {
2480 private static final long serialVersionUID = -7647078645895051609L;
2481
2482 /** Underlying map */
2483 private final ConcurrentSkipListMap<K,V> m;
2484 /** lower bound key, or null if from start */
2485 private final K lo;
2486 /** upper bound key, or null if to end */
2487 private final K hi;
2488 /** inclusion flag for lo */
2489 private final boolean loInclusive;
2490 /** inclusion flag for hi */
2491 private final boolean hiInclusive;
2492 /** direction */
2493 private final boolean isDescending;
2494
2495 // Lazily initialized view holders
2496 private transient KeySet<K> keySetView;
2497 private transient Set<Map.Entry<K,V>> entrySetView;
2498 private transient Collection<V> valuesView;
2499
2500 /**
2501 * Creates a new submap, initializing all fields
2502 */
2503 SubMap(ConcurrentSkipListMap<K,V> map,
2504 K fromKey, boolean fromInclusive,
2505 K toKey, boolean toInclusive,
2506 boolean isDescending) {
2507 if (fromKey != null && toKey != null &&
2508 map.compare(fromKey, toKey) > 0)
2509 throw new IllegalArgumentException("inconsistent range");
2510 this.m = map;
2511 this.lo = fromKey;
2512 this.hi = toKey;
2513 this.loInclusive = fromInclusive;
2514 this.hiInclusive = toInclusive;
2515 this.isDescending = isDescending;
2516 }
2517
2518 /* ---------------- Utilities -------------- */
2519
2520 private boolean tooLow(K key) {
2521 if (lo != null) {
2522 int c = m.compare(key, lo);
2523 if (c < 0 || (c == 0 && !loInclusive))
2524 return true;
2525 }
2526 return false;
2527 }
2528
2529 private boolean tooHigh(K key) {
2530 if (hi != null) {
2531 int c = m.compare(key, hi);
2532 if (c > 0 || (c == 0 && !hiInclusive))
2533 return true;
2534 }
2535 return false;
2536 }
2537
2538 private boolean inBounds(K key) {
2539 return !tooLow(key) && !tooHigh(key);
2540 }
2541
2542 private void checkKeyBounds(K key) throws IllegalArgumentException {
2543 if (key == null)
2544 throw new NullPointerException();
2545 if (!inBounds(key))
2546 throw new IllegalArgumentException("key out of range");
2547 }
2548
2549 /**
2550 * Returns true if node key is less than upper bound of range
2551 */
2552 private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
2553 if (n == null)
2554 return false;
2555 if (hi == null)
2556 return true;
2557 K k = n.key;
2558 if (k == null) // pass by markers and headers
2559 return true;
2560 int c = m.compare(k, hi);
2561 if (c > 0 || (c == 0 && !hiInclusive))
2562 return false;
2563 return true;
2564 }
2565
2566 /**
2567 * Returns lowest node. This node might not be in range, so
2568 * most usages need to check bounds
2569 */
2570 private ConcurrentSkipListMap.Node<K,V> loNode() {
2571 if (lo == null)
2572 return m.findFirst();
2573 else if (loInclusive)
2574 return m.findNear(lo, m.GT|m.EQ);
2575 else
2576 return m.findNear(lo, m.GT);
2577 }
2578
2579 /**
2580 * Returns highest node. This node might not be in range, so
2581 * most usages need to check bounds
2582 */
2583 private ConcurrentSkipListMap.Node<K,V> hiNode() {
2584 if (hi == null)
2585 return m.findLast();
2586 else if (hiInclusive)
2587 return m.findNear(hi, m.LT|m.EQ);
2588 else
2589 return m.findNear(hi, m.LT);
2590 }
2591
2592 /**
2593 * Returns lowest absolute key (ignoring directonality)
2594 */
2595 private K lowestKey() {
2596 ConcurrentSkipListMap.Node<K,V> n = loNode();
2597 if (isBeforeEnd(n))
2598 return n.key;
2599 else
2600 throw new NoSuchElementException();
2601 }
2602
2603 /**
2604 * Returns highest absolute key (ignoring directonality)
2605 */
2606 private K highestKey() {
2607 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2608 if (n != null) {
2609 K last = n.key;
2610 if (inBounds(last))
2611 return last;
2612 }
2613 throw new NoSuchElementException();
2614 }
2615
2616 private Map.Entry<K,V> lowestEntry() {
2617 for (;;) {
2618 ConcurrentSkipListMap.Node<K,V> n = loNode();
2619 if (!isBeforeEnd(n))
2620 return null;
2621 Map.Entry<K,V> e = n.createSnapshot();
2622 if (e != null)
2623 return e;
2624 }
2625 }
2626
2627 private Map.Entry<K,V> highestEntry() {
2628 for (;;) {
2629 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2630 if (n == null || !inBounds(n.key))
2631 return null;
2632 Map.Entry<K,V> e = n.createSnapshot();
2633 if (e != null)
2634 return e;
2635 }
2636 }
2637
2638 private Map.Entry<K,V> removeLowest() {
2639 for (;;) {
2640 Node<K,V> n = loNode();
2641 if (n == null)
2642 return null;
2643 K k = n.key;
2644 if (!inBounds(k))
2645 return null;
2646 V v = m.doRemove(k, null);
2647 if (v != null)
2648 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2649 }
2650 }
2651
2652 private Map.Entry<K,V> removeHighest() {
2653 for (;;) {
2654 Node<K,V> n = hiNode();
2655 if (n == null)
2656 return null;
2657 K k = n.key;
2658 if (!inBounds(k))
2659 return null;
2660 V v = m.doRemove(k, null);
2661 if (v != null)
2662 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2663 }
2664 }
2665
2666 /**
2667 * Submap version of ConcurrentSkipListMap.getNearEntry
2668 */
2669 private Map.Entry<K,V> getNearEntry(K key, int rel) {
2670 if (isDescending) { // adjust relation for direction
2671 if ((rel & m.LT) == 0)
2672 rel |= m.LT;
2673 else
2674 rel &= ~m.LT;
2675 }
2676 if (tooLow(key))
2677 return ((rel & m.LT) != 0) ? null : lowestEntry();
2678 if (tooHigh(key))
2679 return ((rel & m.LT) != 0) ? highestEntry() : null;
2680 for (;;) {
2681 Node<K,V> n = m.findNear(key, rel);
2682 if (n == null || !inBounds(n.key))
2683 return null;
2684 K k = n.key;
2685 V v = n.getValidValue();
2686 if (v != null)
2687 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2688 }
2689 }
2690
2691 // Almost the same as getNearEntry, except for keys
2692 private K getNearKey(K key, int rel) {
2693 if (isDescending) { // adjust relation for direction
2694 if ((rel & m.LT) == 0)
2695 rel |= m.LT;
2696 else
2697 rel &= ~m.LT;
2698 }
2699 if (tooLow(key)) {
2700 if ((rel & m.LT) == 0) {
2701 ConcurrentSkipListMap.Node<K,V> n = loNode();
2702 if (isBeforeEnd(n))
2703 return n.key;
2704 }
2705 return null;
2706 }
2707 if (tooHigh(key)) {
2708 if ((rel & m.LT) != 0) {
2709 ConcurrentSkipListMap.Node<K,V> n = hiNode();
2710 if (n != null) {
2711 K last = n.key;
2712 if (inBounds(last))
2713 return last;
2714 }
2715 }
2716 return null;
2717 }
2718 for (;;) {
2719 Node<K,V> n = m.findNear(key, rel);
2720 if (n == null || !inBounds(n.key))
2721 return null;
2722 K k = n.key;
2723 V v = n.getValidValue();
2724 if (v != null)
2725 return k;
2726 }
2727 }
2728
2729 /* ---------------- Map API methods -------------- */
2730
2731 public boolean containsKey(Object key) {
2732 if (key == null) throw new NullPointerException();
2733 K k = (K)key;
2734 return inBounds(k) && m.containsKey(k);
2735 }
2736
2737 public V get(Object key) {
2738 if (key == null) throw new NullPointerException();
2739 K k = (K)key;
2740 return ((!inBounds(k)) ? null : m.get(k));
2741 }
2742
2743 public V put(K key, V value) {
2744 checkKeyBounds(key);
2745 return m.put(key, value);
2746 }
2747
2748 public V remove(Object key) {
2749 K k = (K)key;
2750 return (!inBounds(k)) ? null : m.remove(k);
2751 }
2752
2753 public int size() {
2754 long count = 0;
2755 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2756 isBeforeEnd(n);
2757 n = n.next) {
2758 if (n.getValidValue() != null)
2759 ++count;
2760 }
2761 return count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)count;
2762 }
2763
2764 public boolean isEmpty() {
2765 return !isBeforeEnd(loNode());
2766 }
2767
2768 public boolean containsValue(Object value) {
2769 if (value == null)
2770 throw new NullPointerException();
2771 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2772 isBeforeEnd(n);
2773 n = n.next) {
2774 V v = n.getValidValue();
2775 if (v != null && value.equals(v))
2776 return true;
2777 }
2778 return false;
2779 }
2780
2781 public void clear() {
2782 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2783 isBeforeEnd(n);
2784 n = n.next) {
2785 if (n.getValidValue() != null)
2786 m.remove(n.key);
2787 }
2788 }
2789
2790 /* ---------------- ConcurrentMap API methods -------------- */
2791
2792 public V putIfAbsent(K key, V value) {
2793 checkKeyBounds(key);
2794 return m.putIfAbsent(key, value);
2795 }
2796
2797 public boolean remove(Object key, Object value) {
2798 K k = (K)key;
2799 return inBounds(k) && m.remove(k, value);
2800 }
2801
2802 public boolean replace(K key, V oldValue, V newValue) {
2803 checkKeyBounds(key);
2804 return m.replace(key, oldValue, newValue);
2805 }
2806
2807 public V replace(K key, V value) {
2808 checkKeyBounds(key);
2809 return m.replace(key, value);
2810 }
2811
2812 /* ---------------- SortedMap API methods -------------- */
2813
2814 public Comparator<? super K> comparator() {
2815 Comparator<? super K> cmp = m.comparator();
2816 if (isDescending)
2817 return Collections.reverseOrder(cmp);
2818 else
2819 return cmp;
2820 }
2821
2822 /**
2823 * Utility to create submaps, where given bounds override
2824 * unbounded(null) ones and/or are checked against bounded ones.
2825 */
2826 private SubMap<K,V> newSubMap(K fromKey,
2827 boolean fromInclusive,
2828 K toKey,
2829 boolean toInclusive) {
2830 if (isDescending) { // flip senses
2831 K tk = fromKey;
2832 fromKey = toKey;
2833 toKey = tk;
2834 boolean ti = fromInclusive;
2835 fromInclusive = toInclusive;
2836 toInclusive = ti;
2837 }
2838 if (lo != null) {
2839 if (fromKey == null) {
2840 fromKey = lo;
2841 fromInclusive = loInclusive;
2842 }
2843 else {
2844 int c = m.compare(fromKey, lo);
2845 if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2846 throw new IllegalArgumentException("key out of range");
2847 }
2848 }
2849 if (hi != null) {
2850 if (toKey == null) {
2851 toKey = hi;
2852 toInclusive = hiInclusive;
2853 }
2854 else {
2855 int c = m.compare(toKey, hi);
2856 if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2857 throw new IllegalArgumentException("key out of range");
2858 }
2859 }
2860 return new SubMap<K,V>(m, fromKey, fromInclusive,
2861 toKey, toInclusive, isDescending);
2862 }
2863
2864 public SubMap<K,V> subMap(K fromKey,
2865 boolean fromInclusive,
2866 K toKey,
2867 boolean toInclusive) {
2868 if (fromKey == null || toKey == null)
2869 throw new NullPointerException();
2870 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2871 }
2872
2873 public SubMap<K,V> headMap(K toKey,
2874 boolean inclusive) {
2875 if (toKey == null)
2876 throw new NullPointerException();
2877 return newSubMap(null, false, toKey, inclusive);
2878 }
2879
2880 public SubMap<K,V> tailMap(K fromKey,
2881 boolean inclusive) {
2882 if (fromKey == null)
2883 throw new NullPointerException();
2884 return newSubMap(fromKey, inclusive, null, false);
2885 }
2886
2887 public SubMap<K,V> subMap(K fromKey, K toKey) {
2888 return subMap(fromKey, true, toKey, false);
2889 }
2890
2891 public SubMap<K,V> headMap(K toKey) {
2892 return headMap(toKey, false);
2893 }
2894
2895 public SubMap<K,V> tailMap(K fromKey) {
2896 return tailMap(fromKey, true);
2897 }
2898
2899 public SubMap<K,V> descendingMap() {
2900 return new SubMap<K,V>(m, lo, loInclusive,
2901 hi, hiInclusive, !isDescending);
2902 }
2903
2904 /* ---------------- Relational methods -------------- */
2905
2906 public Map.Entry<K,V> ceilingEntry(K key) {
2907 return getNearEntry(key, (m.GT|m.EQ));
2908 }
2909
2910 public K ceilingKey(K key) {
2911 return getNearKey(key, (m.GT|m.EQ));
2912 }
2913
2914 public Map.Entry<K,V> lowerEntry(K key) {
2915 return getNearEntry(key, (m.LT));
2916 }
2917
2918 public K lowerKey(K key) {
2919 return getNearKey(key, (m.LT));
2920 }
2921
2922 public Map.Entry<K,V> floorEntry(K key) {
2923 return getNearEntry(key, (m.LT|m.EQ));
2924 }
2925
2926 public K floorKey(K key) {
2927 return getNearKey(key, (m.LT|m.EQ));
2928 }
2929
2930 public Map.Entry<K,V> higherEntry(K key) {
2931 return getNearEntry(key, (m.GT));
2932 }
2933
2934 public K higherKey(K key) {
2935 return getNearKey(key, (m.GT));
2936 }
2937
2938 public K firstKey() {
2939 return isDescending ? highestKey() : lowestKey();
2940 }
2941
2942 public K lastKey() {
2943 return isDescending ? lowestKey() : highestKey();
2944 }
2945
2946 public Map.Entry<K,V> firstEntry() {
2947 return isDescending ? highestEntry() : lowestEntry();
2948 }
2949
2950 public Map.Entry<K,V> lastEntry() {
2951 return isDescending ? lowestEntry() : highestEntry();
2952 }
2953
2954 public Map.Entry<K,V> pollFirstEntry() {
2955 return isDescending ? removeHighest() : removeLowest();
2956 }
2957
2958 public Map.Entry<K,V> pollLastEntry() {
2959 return isDescending ? removeLowest() : removeHighest();
2960 }
2961
2962 /* ---------------- Submap Views -------------- */
2963
2964 public NavigableSet<K> keySet() {
2965 KeySet<K> ks = keySetView;
2966 return (ks != null) ? ks : (keySetView = new KeySet(this));
2967 }
2968
2969 public NavigableSet<K> navigableKeySet() {
2970 KeySet<K> ks = keySetView;
2971 return (ks != null) ? ks : (keySetView = new KeySet(this));
2972 }
2973
2974 public Collection<V> values() {
2975 Collection<V> vs = valuesView;
2976 return (vs != null) ? vs : (valuesView = new Values(this));
2977 }
2978
2979 public Set<Map.Entry<K,V>> entrySet() {
2980 Set<Map.Entry<K,V>> es = entrySetView;
2981 return (es != null) ? es : (entrySetView = new EntrySet(this));
2982 }
2983
2984 public NavigableSet<K> descendingKeySet() {
2985 return descendingMap().navigableKeySet();
2986 }
2987
2988 Iterator<K> keyIterator() {
2989 return new SubMapKeyIterator();
2990 }
2991
2992 Iterator<V> valueIterator() {
2993 return new SubMapValueIterator();
2994 }
2995
2996 Iterator<Map.Entry<K,V>> entryIterator() {
2997 return new SubMapEntryIterator();
2998 }
2999
3000 /**
3001 * Variant of main Iter class to traverse through submaps.
3002 */
3003 abstract class SubMapIter<T> implements Iterator<T> {
3004 /** the last node returned by next() */
3005 Node<K,V> lastReturned;
3006 /** the next node to return from next(); */
3007 Node<K,V> next;
3008 /** Cache of next value field to maintain weak consistency */
3009 V nextValue;
3010
3011 SubMapIter() {
3012 for (;;) {
3013 next = isDescending ? hiNode() : loNode();
3014 if (next == null)
3015 break;
3016 Object x = next.value;
3017 if (x != null && x != next) {
3018 if (! inBounds(next.key))
3019 next = null;
3020 else
3021 nextValue = (V) x;
3022 break;
3023 }
3024 }
3025 }
3026
3027 public final boolean hasNext() {
3028 return next != null;
3029 }
3030
3031 final void advance() {
3032 if (next == null)
3033 throw new NoSuchElementException();
3034 lastReturned = next;
3035 if (isDescending)
3036 descend();
3037 else
3038 ascend();
3039 }
3040
3041 private void ascend() {
3042 for (;;) {
3043 next = next.next;
3044 if (next == null)
3045 break;
3046 Object x = next.value;
3047 if (x != null && x != next) {
3048 if (tooHigh(next.key))
3049 next = null;
3050 else
3051 nextValue = (V) x;
3052 break;
3053 }
3054 }
3055 }
3056
3057 private void descend() {
3058 for (;;) {
3059 next = m.findNear(lastReturned.key, LT);
3060 if (next == null)
3061 break;
3062 Object x = next.value;
3063 if (x != null && x != next) {
3064 if (tooLow(next.key))
3065 next = null;
3066 else
3067 nextValue = (V) x;
3068 break;
3069 }
3070 }
3071 }
3072
3073 public void remove() {
3074 Node<K,V> l = lastReturned;
3075 if (l == null)
3076 throw new IllegalStateException();
3077 m.remove(l.key);
3078 lastReturned = null;
3079 }
3080
3081 }
3082
3083 final class SubMapValueIterator extends SubMapIter<V> {
3084 public V next() {
3085 V v = nextValue;
3086 advance();
3087 return v;
3088 }
3089 }
3090
3091 final class SubMapKeyIterator extends SubMapIter<K> {
3092 public K next() {
3093 Node<K,V> n = next;
3094 advance();
3095 return n.key;
3096 }
3097 }
3098
3099 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3100 public Map.Entry<K,V> next() {
3101 Node<K,V> n = next;
3102 V v = nextValue;
3103 advance();
3104 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3105 }
3106 }
3107 }
3108
3109 // Unsafe mechanics
3110 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
3111 private static final long headOffset =
3112 objectFieldOffset(UNSAFE, "head", ConcurrentSkipListMap.class);
3113
3114 static long objectFieldOffset(sun.misc.Unsafe UNSAFE,
3115 String field, Class<?> klazz) {
3116 try {
3117 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
3118 } catch (NoSuchFieldException e) {
3119 // Convert Exception to corresponding Error
3120 NoSuchFieldError error = new NoSuchFieldError(field);
3121 error.initCause(e);
3122 throw error;
3123 }
3124 }
3125
3126 }