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

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