ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.12
Committed: Mon May 2 03:04:41 2005 UTC (19 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.11: +3 -3 lines
Log Message:
4 stray parens

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