ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.6
Committed: Tue Mar 22 01:30:18 2005 UTC (19 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.5: +87 -15 lines
Log Message:
NavigableMap.subMap -> NavigableMap.navigableSubMap, and associated changes

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 * Return true if this node is a marker. This method isn't
416 * actually called in an 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 * Return 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 * Return 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 * Create and return 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<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 * Compare 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 * Return 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 * Return 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 * Return 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<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 * Return 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<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<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 * Perform 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<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<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 * Return 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 * Create and add index nodes for 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 * Add 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<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<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 * Remove first entry; return 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 * Clear 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 * Remove first entry; return 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<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 * Remove last entry; return 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<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 * Return 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 * Return 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 * Return 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 * Return 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 * Find and remove 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 * Find and remove 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 the <tt>Map</tt> instance 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 <tt>Map</tt> instance 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 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 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 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<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 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<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 if (fromKey == null || toKey == null)
2273 throw new NullPointerException();
2274 return new ConcurrentSkipListSubMap(this, fromKey, toKey);
2275 }
2276
2277 /**
2278 * Equivalent to <tt>navigableHeadMap</tt> but with a return
2279 * type conforming to the <tt>SortedMap</tt> interface.
2280 * @param toKey high endpoint (exclusive) of the headMap.
2281 * @return a view of the portion of this map whose keys are
2282 * strictly less than <tt>toKey</tt>.
2283 *
2284 * @throws ClassCastException if <tt>toKey</tt> is not compatible
2285 * with this map's comparator (or, if the map has no comparator,
2286 * if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
2287 * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt>.
2288 */
2289 public SortedMap<K,V> headMap(K toKey) {
2290 if (toKey == null)
2291 throw new NullPointerException();
2292 return new ConcurrentSkipListSubMap(this, null, toKey);
2293 }
2294
2295 /**
2296 * Equivalent to <tt>navigableTailMap</tt> but with a return
2297 * type conforming to the <tt>SortedMap</tt> interface.
2298 * @param fromKey low endpoint (inclusive) of the tailMap.
2299 * @return a view of the portion of this map whose keys are
2300 * greater than or equal to <tt>fromKey</tt>.
2301 * @throws ClassCastException if <tt>fromKey</tt> is not
2302 * compatible with this map's comparator (or, if the map has no
2303 * comparator, if <tt>fromKey</tt> does not implement
2304 * <tt>Comparable</tt>).
2305 * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt>.
2306 */
2307 public SortedMap<K,V> tailMap(K fromKey) {
2308 if (fromKey == null)
2309 throw new NullPointerException();
2310 return new ConcurrentSkipListSubMap(this, fromKey, null);
2311 }
2312
2313 /* ---------------- Relational operations -------------- */
2314
2315 /**
2316 * Returns a key-value mapping associated with the least key
2317 * greater than or equal to the given key, or <tt>null</tt> if
2318 * there is no such entry. The returned entry does <em>not</em>
2319 * support the <tt>Entry.setValue</tt> method.
2320 *
2321 * @param key the key.
2322 * @return an Entry associated with ceiling of given key, or
2323 * <tt>null</tt> if there is no such Entry.
2324 * @throws ClassCastException if key cannot be compared with the
2325 * keys currently in the map.
2326 * @throws NullPointerException if key is <tt>null</tt>.
2327 */
2328 public Map.Entry<K,V> ceilingEntry(K key) {
2329 return getNear(key, GT|EQ);
2330 }
2331
2332 /**
2333 * Returns least key greater than or equal to the given key, or
2334 * <tt>null</tt> if there is no such key.
2335 *
2336 * @param key the key.
2337 * @return the ceiling key, or <tt>null</tt>
2338 * if there is no such key.
2339 * @throws ClassCastException if key cannot be compared with the keys
2340 * currently in the map.
2341 * @throws NullPointerException if key is <tt>null</tt>.
2342 */
2343 public K ceilingKey(K key) {
2344 Node<K,V> n = findNear(key, GT|EQ);
2345 return (n == null)? null : n.key;
2346 }
2347
2348 /**
2349 * Returns a key-value mapping associated with the greatest
2350 * key strictly less than the given key, or <tt>null</tt> if there is no
2351 * such entry. The returned entry does <em>not</em> support
2352 * the <tt>Entry.setValue</tt> method.
2353 *
2354 * @param key the key.
2355 * @return an Entry with greatest key less than the given
2356 * key, or <tt>null</tt> if there is no such Entry.
2357 * @throws ClassCastException if key cannot be compared with the keys
2358 * currently in the map.
2359 * @throws NullPointerException if key is <tt>null</tt>.
2360 */
2361 public Map.Entry<K,V> lowerEntry(K key) {
2362 return getNear(key, LT);
2363 }
2364
2365 /**
2366 * Returns the greatest key strictly less than the given key, or
2367 * <tt>null</tt> if there is no such key.
2368 *
2369 * @param key the key.
2370 * @return the greatest key less than the given
2371 * key, or <tt>null</tt> if there is no such key.
2372 * @throws ClassCastException if key cannot be compared with the keys
2373 * currently in the map.
2374 * @throws NullPointerException if key is <tt>null</tt>.
2375 */
2376 public K lowerKey(K key) {
2377 Node<K,V> n = findNear(key, LT);
2378 return (n == null)? null : n.key;
2379 }
2380
2381 /**
2382 * Returns a key-value mapping associated with the greatest key
2383 * less than or equal to the given key, or <tt>null</tt> if there
2384 * is no such entry. The returned entry does <em>not</em> support
2385 * the <tt>Entry.setValue</tt> method.
2386 *
2387 * @param key the key.
2388 * @return an Entry associated with floor of given key, or <tt>null</tt>
2389 * if there is no such Entry.
2390 * @throws ClassCastException if key cannot be compared with the keys
2391 * currently in the map.
2392 * @throws NullPointerException if key is <tt>null</tt>.
2393 */
2394 public Map.Entry<K,V> floorEntry(K key) {
2395 return getNear(key, LT|EQ);
2396 }
2397
2398 /**
2399 * Returns the greatest key
2400 * less than or equal to the given key, or <tt>null</tt> if there
2401 * is no such key.
2402 *
2403 * @param key the key.
2404 * @return the floor of given key, or <tt>null</tt> if there is no
2405 * such key.
2406 * @throws ClassCastException if key cannot be compared with the keys
2407 * currently in the map.
2408 * @throws NullPointerException if key is <tt>null</tt>.
2409 */
2410 public K floorKey(K key) {
2411 Node<K,V> n = findNear(key, LT|EQ);
2412 return (n == null)? null : n.key;
2413 }
2414
2415 /**
2416 * Returns a key-value mapping associated with the least key
2417 * strictly greater than the given key, or <tt>null</tt> if there
2418 * is no such entry. The returned entry does <em>not</em> support
2419 * the <tt>Entry.setValue</tt> method.
2420 *
2421 * @param key the key.
2422 * @return an Entry with least key greater than the given key, or
2423 * <tt>null</tt> if there is no such Entry.
2424 * @throws ClassCastException if key cannot be compared with the keys
2425 * currently in the map.
2426 * @throws NullPointerException if key is <tt>null</tt>.
2427 */
2428 public Map.Entry<K,V> higherEntry(K key) {
2429 return getNear(key, GT);
2430 }
2431
2432 /**
2433 * Returns the least key strictly greater than the given key, or
2434 * <tt>null</tt> if there is no such key.
2435 *
2436 * @param key the key.
2437 * @return the least key greater than the given key, or
2438 * <tt>null</tt> if there is no such key.
2439 * @throws ClassCastException if key cannot be compared with the keys
2440 * currently in the map.
2441 * @throws NullPointerException if key is <tt>null</tt>.
2442 */
2443 public K higherKey(K key) {
2444 Node<K,V> n = findNear(key, GT);
2445 return (n == null)? null : n.key;
2446 }
2447
2448 /**
2449 * Returns a key-value mapping associated with the least
2450 * key in this map, or <tt>null</tt> if the map is empty.
2451 * The returned entry does <em>not</em> support
2452 * the <tt>Entry.setValue</tt> method.
2453 *
2454 * @return an Entry with least key, or <tt>null</tt>
2455 * if the map is empty.
2456 */
2457 public Map.Entry<K,V> firstEntry() {
2458 for (;;) {
2459 Node<K,V> n = findFirst();
2460 if (n == null)
2461 return null;
2462 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2463 if (e != null)
2464 return e;
2465 }
2466 }
2467
2468 /**
2469 * Returns a key-value mapping associated with the greatest
2470 * key in this map, or <tt>null</tt> if the map is empty.
2471 * The returned entry does <em>not</em> support
2472 * the <tt>Entry.setValue</tt> method.
2473 *
2474 * @return an Entry with greatest key, or <tt>null</tt>
2475 * if the map is empty.
2476 */
2477 public Map.Entry<K,V> lastEntry() {
2478 for (;;) {
2479 Node<K,V> n = findLast();
2480 if (n == null)
2481 return null;
2482 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2483 if (e != null)
2484 return e;
2485 }
2486 }
2487
2488 /**
2489 * Removes and returns a key-value mapping associated with
2490 * the least key in this map, or <tt>null</tt> if the map is empty.
2491 * The returned entry does <em>not</em> support
2492 * the <tt>Entry.setValue</tt> method.
2493 *
2494 * @return the removed first entry of this map, or <tt>null</tt>
2495 * if the map is empty.
2496 */
2497 public Map.Entry<K,V> pollFirstEntry() {
2498 return (AbstractMap.SimpleImmutableEntry<K,V>)doRemoveFirst(false);
2499 }
2500
2501 /**
2502 * Removes and returns a key-value mapping associated with
2503 * the greatest key in this map, or <tt>null</tt> if the map is empty.
2504 * The returned entry does <em>not</em> support
2505 * the <tt>Entry.setValue</tt> method.
2506 *
2507 * @return the removed last entry of this map, or <tt>null</tt>
2508 * if the map is empty.
2509 */
2510 public Map.Entry<K,V> pollLastEntry() {
2511 return (AbstractMap.SimpleImmutableEntry<K,V>)doRemoveLast(false);
2512 }
2513
2514
2515 /* ---------------- Iterators -------------- */
2516
2517 /**
2518 * Base of ten kinds of iterator classes:
2519 * ascending: {map, submap} X {key, value, entry}
2520 * descending: {map, submap} X {key, entry}
2521 */
2522 abstract class Iter {
2523 /** the last node returned by next() */
2524 Node<K,V> last;
2525 /** the next node to return from next(); */
2526 Node<K,V> next;
2527 /** Cache of next value field to maintain weak consistency */
2528 Object nextValue;
2529
2530 Iter() {}
2531
2532 public final boolean hasNext() {
2533 return next != null;
2534 }
2535
2536 /** initialize ascending iterator for entire range */
2537 final void initAscending() {
2538 for (;;) {
2539 next = findFirst();
2540 if (next == null)
2541 break;
2542 nextValue = next.value;
2543 if (nextValue != null && nextValue != next)
2544 break;
2545 }
2546 }
2547
2548 /**
2549 * initialize ascending iterator starting at given least key,
2550 * or first node if least is <tt>null</tt>, but not greater or
2551 * equal to fence, or end if fence is <tt>null</tt>.
2552 */
2553 final void initAscending(K least, K fence) {
2554 for (;;) {
2555 next = findCeiling(least);
2556 if (next == null)
2557 break;
2558 nextValue = next.value;
2559 if (nextValue != null && nextValue != next) {
2560 if (fence != null && compare(fence, next.key) <= 0) {
2561 next = null;
2562 nextValue = null;
2563 }
2564 break;
2565 }
2566 }
2567 }
2568 /** advance next to higher entry */
2569 final void ascend() {
2570 if ((last = next) == null)
2571 throw new NoSuchElementException();
2572 for (;;) {
2573 next = next.next;
2574 if (next == null)
2575 break;
2576 nextValue = next.value;
2577 if (nextValue != null && nextValue != next)
2578 break;
2579 }
2580 }
2581
2582 /**
2583 * Version of ascend for submaps to stop at fence
2584 */
2585 final void ascend(K fence) {
2586 if ((last = next) == null)
2587 throw new NoSuchElementException();
2588 for (;;) {
2589 next = next.next;
2590 if (next == null)
2591 break;
2592 nextValue = next.value;
2593 if (nextValue != null && nextValue != next) {
2594 if (fence != null && compare(fence, next.key) <= 0) {
2595 next = null;
2596 nextValue = null;
2597 }
2598 break;
2599 }
2600 }
2601 }
2602
2603 /** initialize descending iterator for entire range */
2604 final void initDescending() {
2605 for (;;) {
2606 next = findLast();
2607 if (next == null)
2608 break;
2609 nextValue = next.value;
2610 if (nextValue != null && nextValue != next)
2611 break;
2612 }
2613 }
2614
2615 /**
2616 * initialize descending iterator starting at key less
2617 * than or equal to given fence key, or
2618 * last node if fence is <tt>null</tt>, but not less than
2619 * least, or beginning if lest is <tt>null</tt>.
2620 */
2621 final void initDescending(K least, K fence) {
2622 for (;;) {
2623 next = findLower(fence);
2624 if (next == null)
2625 break;
2626 nextValue = next.value;
2627 if (nextValue != null && nextValue != next) {
2628 if (least != null && compare(least, next.key) > 0) {
2629 next = null;
2630 nextValue = null;
2631 }
2632 break;
2633 }
2634 }
2635 }
2636
2637 /** advance next to lower entry */
2638 final void descend() {
2639 if ((last = next) == null)
2640 throw new NoSuchElementException();
2641 K k = last.key;
2642 for (;;) {
2643 next = findNear(k, LT);
2644 if (next == null)
2645 break;
2646 nextValue = next.value;
2647 if (nextValue != null && nextValue != next)
2648 break;
2649 }
2650 }
2651
2652 /**
2653 * Version of descend for submaps to stop at least
2654 */
2655 final void descend(K least) {
2656 if ((last = next) == null)
2657 throw new NoSuchElementException();
2658 K k = last.key;
2659 for (;;) {
2660 next = findNear(k, LT);
2661 if (next == null)
2662 break;
2663 nextValue = next.value;
2664 if (nextValue != null && nextValue != next) {
2665 if (least != null && compare(least, next.key) > 0) {
2666 next = null;
2667 nextValue = null;
2668 }
2669 break;
2670 }
2671 }
2672 }
2673
2674 public void remove() {
2675 Node<K,V> l = last;
2676 if (l == null)
2677 throw new IllegalStateException();
2678 // It would not be worth all of the overhead to directly
2679 // unlink from here. Using remove is fast enough.
2680 ConcurrentSkipListMap.this.remove(l.key);
2681 }
2682
2683 }
2684
2685 final class ValueIterator extends Iter implements Iterator<V> {
2686 ValueIterator() {
2687 initAscending();
2688 }
2689 public V next() {
2690 Object v = nextValue;
2691 ascend();
2692 return (V)v;
2693 }
2694 }
2695
2696 final class KeyIterator extends Iter implements Iterator<K> {
2697 KeyIterator() {
2698 initAscending();
2699 }
2700 public K next() {
2701 Node<K,V> n = next;
2702 ascend();
2703 return n.key;
2704 }
2705 }
2706
2707 class SubMapValueIterator extends Iter implements Iterator<V> {
2708 final K fence;
2709 SubMapValueIterator(K least, K fence) {
2710 initAscending(least, fence);
2711 this.fence = fence;
2712 }
2713
2714 public V next() {
2715 Object v = nextValue;
2716 ascend(fence);
2717 return (V)v;
2718 }
2719 }
2720
2721 final class SubMapKeyIterator extends Iter implements Iterator<K> {
2722 final K fence;
2723 SubMapKeyIterator(K least, K fence) {
2724 initAscending(least, fence);
2725 this.fence = fence;
2726 }
2727
2728 public K next() {
2729 Node<K,V> n = next;
2730 ascend(fence);
2731 return n.key;
2732 }
2733 }
2734
2735 final class DescendingKeyIterator extends Iter implements Iterator<K> {
2736 DescendingKeyIterator() {
2737 initDescending();
2738 }
2739 public K next() {
2740 Node<K,V> n = next;
2741 descend();
2742 return n.key;
2743 }
2744 }
2745
2746 final class DescendingSubMapKeyIterator extends Iter implements Iterator<K> {
2747 final K least;
2748 DescendingSubMapKeyIterator(K least, K fence) {
2749 initDescending(least, fence);
2750 this.least = least;
2751 }
2752
2753 public K next() {
2754 Node<K,V> n = next;
2755 descend(least);
2756 return n.key;
2757 }
2758 }
2759
2760 /**
2761 * Entry iterators use the same trick as in ConcurrentHashMap and
2762 * elsewhere of using the iterator itself to represent entries,
2763 * thus avoiding having to create entry objects in next().
2764 */
2765 abstract class EntryIter extends Iter implements Map.Entry<K,V> {
2766 /** Cache of last value returned */
2767 Object lastValue;
2768
2769 EntryIter() {
2770 }
2771
2772 public K getKey() {
2773 Node<K,V> l = last;
2774 if (l == null)
2775 throw new IllegalStateException();
2776 return l.key;
2777 }
2778
2779 public V getValue() {
2780 Object v = lastValue;
2781 if (last == null || v == null)
2782 throw new IllegalStateException();
2783 return (V)v;
2784 }
2785
2786 public V setValue(V value) {
2787 throw new UnsupportedOperationException();
2788 }
2789
2790 public boolean equals(Object o) {
2791 // If not acting as entry, just use default.
2792 if (last == null)
2793 return super.equals(o);
2794 if (!(o instanceof Map.Entry))
2795 return false;
2796 Map.Entry e = (Map.Entry)o;
2797 return (getKey().equals(e.getKey()) &&
2798 getValue().equals(e.getValue()));
2799 }
2800
2801 public int hashCode() {
2802 // If not acting as entry, just use default.
2803 if (last == null)
2804 return super.hashCode();
2805 return getKey().hashCode() ^ getValue().hashCode();
2806 }
2807
2808 public String toString() {
2809 // If not acting as entry, just use default.
2810 if (last == null)
2811 return super.toString();
2812 return getKey() + "=" + getValue();
2813 }
2814 }
2815
2816 final class EntryIterator extends EntryIter
2817 implements Iterator<Map.Entry<K,V>> {
2818 EntryIterator() {
2819 initAscending();
2820 }
2821 public Map.Entry<K,V> next() {
2822 lastValue = nextValue;
2823 ascend();
2824 return this;
2825 }
2826 }
2827
2828 final class SubMapEntryIterator extends EntryIter
2829 implements Iterator<Map.Entry<K,V>> {
2830 final K fence;
2831 SubMapEntryIterator(K least, K fence) {
2832 initAscending(least, fence);
2833 this.fence = fence;
2834 }
2835
2836 public Map.Entry<K,V> next() {
2837 lastValue = nextValue;
2838 ascend(fence);
2839 return this;
2840 }
2841 }
2842
2843 final class DescendingEntryIterator extends EntryIter
2844 implements Iterator<Map.Entry<K,V>> {
2845 DescendingEntryIterator() {
2846 initDescending();
2847 }
2848 public Map.Entry<K,V> next() {
2849 lastValue = nextValue;
2850 descend();
2851 return this;
2852 }
2853 }
2854
2855 final class DescendingSubMapEntryIterator extends EntryIter
2856 implements Iterator<Map.Entry<K,V>> {
2857 final K least;
2858 DescendingSubMapEntryIterator(K least, K fence) {
2859 initDescending(least, fence);
2860 this.least = least;
2861 }
2862
2863 public Map.Entry<K,V> next() {
2864 lastValue = nextValue;
2865 descend(least);
2866 return this;
2867 }
2868 }
2869
2870 // Factory methods for iterators needed by submaps and/or
2871 // ConcurrentSkipListSet
2872
2873 Iterator<K> keyIterator() {
2874 return new KeyIterator();
2875 }
2876
2877 Iterator<K> descendingKeyIterator() {
2878 return new DescendingKeyIterator();
2879 }
2880
2881 SubMapEntryIterator subMapEntryIterator(K least, K fence) {
2882 return new SubMapEntryIterator(least, fence);
2883 }
2884
2885 DescendingSubMapEntryIterator descendingSubMapEntryIterator(K least, K fence) {
2886 return new DescendingSubMapEntryIterator(least, fence);
2887 }
2888
2889 SubMapKeyIterator subMapKeyIterator(K least, K fence) {
2890 return new SubMapKeyIterator(least, fence);
2891 }
2892
2893 DescendingSubMapKeyIterator descendingSubMapKeyIterator(K least, K fence) {
2894 return new DescendingSubMapKeyIterator(least, fence);
2895 }
2896
2897 SubMapValueIterator subMapValueIterator(K least, K fence) {
2898 return new SubMapValueIterator(least, fence);
2899 }
2900
2901 /* ---------------- Views -------------- */
2902
2903 class KeySet extends AbstractSet<K> {
2904 public Iterator<K> iterator() {
2905 return new KeyIterator();
2906 }
2907 public boolean isEmpty() {
2908 return ConcurrentSkipListMap.this.isEmpty();
2909 }
2910 public int size() {
2911 return ConcurrentSkipListMap.this.size();
2912 }
2913 public boolean contains(Object o) {
2914 return ConcurrentSkipListMap.this.containsKey(o);
2915 }
2916 public boolean remove(Object o) {
2917 return ConcurrentSkipListMap.this.removep(o);
2918 }
2919 public void clear() {
2920 ConcurrentSkipListMap.this.clear();
2921 }
2922 public Object[] toArray() {
2923 Collection<K> c = new ArrayList<K>();
2924 for (Iterator<K> i = iterator(); i.hasNext(); )
2925 c.add(i.next());
2926 return c.toArray();
2927 }
2928 public <T> T[] toArray(T[] a) {
2929 Collection<K> c = new ArrayList<K>();
2930 for (Iterator<K> i = iterator(); i.hasNext(); )
2931 c.add(i.next());
2932 return c.toArray(a);
2933 }
2934 }
2935
2936 class DescendingKeySet extends KeySet {
2937 public Iterator<K> iterator() {
2938 return new DescendingKeyIterator();
2939 }
2940 }
2941
2942 final class Values extends AbstractCollection<V> {
2943 public Iterator<V> iterator() {
2944 return new ValueIterator();
2945 }
2946 public boolean isEmpty() {
2947 return ConcurrentSkipListMap.this.isEmpty();
2948 }
2949 public int size() {
2950 return ConcurrentSkipListMap.this.size();
2951 }
2952 public boolean contains(Object o) {
2953 return ConcurrentSkipListMap.this.containsValue(o);
2954 }
2955 public void clear() {
2956 ConcurrentSkipListMap.this.clear();
2957 }
2958 public Object[] toArray() {
2959 Collection<V> c = new ArrayList<V>();
2960 for (Iterator<V> i = iterator(); i.hasNext(); )
2961 c.add(i.next());
2962 return c.toArray();
2963 }
2964 public <T> T[] toArray(T[] a) {
2965 Collection<V> c = new ArrayList<V>();
2966 for (Iterator<V> i = iterator(); i.hasNext(); )
2967 c.add(i.next());
2968 return c.toArray(a);
2969 }
2970 }
2971
2972 class EntrySet extends AbstractSet<Map.Entry<K,V>> {
2973 public Iterator<Map.Entry<K,V>> iterator() {
2974 return new EntryIterator();
2975 }
2976 public boolean contains(Object o) {
2977 if (!(o instanceof Map.Entry))
2978 return false;
2979 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
2980 V v = ConcurrentSkipListMap.this.get(e.getKey());
2981 return v != null && v.equals(e.getValue());
2982 }
2983 public boolean remove(Object o) {
2984 if (!(o instanceof Map.Entry))
2985 return false;
2986 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
2987 return ConcurrentSkipListMap.this.remove(e.getKey(),
2988 e.getValue());
2989 }
2990 public boolean isEmpty() {
2991 return ConcurrentSkipListMap.this.isEmpty();
2992 }
2993 public int size() {
2994 return ConcurrentSkipListMap.this.size();
2995 }
2996 public void clear() {
2997 ConcurrentSkipListMap.this.clear();
2998 }
2999
3000 public Object[] toArray() {
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();
3005 }
3006 public <T> T[] toArray(T[] a) {
3007 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3008 for (Map.Entry e : this)
3009 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3010 return c.toArray(a);
3011 }
3012 }
3013
3014 class DescendingEntrySet extends EntrySet {
3015 public Iterator<Map.Entry<K,V>> iterator() {
3016 return new DescendingEntryIterator();
3017 }
3018 }
3019
3020 /**
3021 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
3022 * represent a subrange of mappings of their underlying
3023 * maps. Instances of this class support all methods of their
3024 * underlying maps, differing in that mappings outside their range are
3025 * ignored, and attempts to add mappings outside their ranges result
3026 * in {@link IllegalArgumentException}. Instances of this class are
3027 * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
3028 * <tt>tailMap</tt> methods of their underlying maps.
3029 */
3030 static class ConcurrentSkipListSubMap<K,V> extends AbstractMap<K,V>
3031 implements ConcurrentNavigableMap<K,V>, java.io.Serializable {
3032
3033 private static final long serialVersionUID = -7647078645895051609L;
3034
3035 /** Underlying map */
3036 private final ConcurrentSkipListMap<K,V> m;
3037 /** lower bound key, or null if from start */
3038 private final K least;
3039 /** upper fence key, or null if to end */
3040 private final K fence;
3041 // Lazily initialized view holders
3042 private transient Set<K> keySetView;
3043 private transient Set<Map.Entry<K,V>> entrySetView;
3044 private transient Collection<V> valuesView;
3045 private transient Set<K> descendingKeySetView;
3046 private transient Set<Map.Entry<K,V>> descendingEntrySetView;
3047
3048 /**
3049 * Creates a new submap.
3050 * @param least inclusive least value, or <tt>null</tt> if from start
3051 * @param fence exclusive upper bound or <tt>null</tt> if to end
3052 * @throws IllegalArgumentException if least and fence nonnull
3053 * and least greater than fence
3054 */
3055 ConcurrentSkipListSubMap(ConcurrentSkipListMap<K,V> map,
3056 K least, K fence) {
3057 if (least != null &&
3058 fence != null &&
3059 map.compare(least, fence) > 0)
3060 throw new IllegalArgumentException("inconsistent range");
3061 this.m = map;
3062 this.least = least;
3063 this.fence = fence;
3064 }
3065
3066 /* ---------------- Utilities -------------- */
3067
3068 boolean inHalfOpenRange(K key) {
3069 return m.inHalfOpenRange(key, least, fence);
3070 }
3071
3072 boolean inOpenRange(K key) {
3073 return m.inOpenRange(key, least, fence);
3074 }
3075
3076 ConcurrentSkipListMap.Node<K,V> firstNode() {
3077 return m.findCeiling(least);
3078 }
3079
3080 ConcurrentSkipListMap.Node<K,V> lastNode() {
3081 return m.findLower(fence);
3082 }
3083
3084 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
3085 return (n != null &&
3086 (fence == null ||
3087 n.key == null || // pass by markers and headers
3088 m.compare(fence, n.key) > 0));
3089 }
3090
3091 void checkKey(K key) throws IllegalArgumentException {
3092 if (!inHalfOpenRange(key))
3093 throw new IllegalArgumentException("key out of range");
3094 }
3095
3096 /**
3097 * Returns underlying map. Needed by ConcurrentSkipListSet
3098 * @return the backing map
3099 */
3100 ConcurrentSkipListMap<K,V> getMap() {
3101 return m;
3102 }
3103
3104 /**
3105 * Returns least key. Needed by ConcurrentSkipListSet
3106 * @return least key or <tt>null</tt> if from start
3107 */
3108 K getLeast() {
3109 return least;
3110 }
3111
3112 /**
3113 * Returns fence key. Needed by ConcurrentSkipListSet
3114 * @return fence key or <tt>null</tt> of to end
3115 */
3116 K getFence() {
3117 return fence;
3118 }
3119
3120
3121 /* ---------------- Map API methods -------------- */
3122
3123 public boolean containsKey(Object key) {
3124 K k = (K)key;
3125 return inHalfOpenRange(k) && m.containsKey(k);
3126 }
3127
3128 public V get(Object key) {
3129 K k = (K)key;
3130 return ((!inHalfOpenRange(k)) ? null : m.get(k));
3131 }
3132
3133 public V put(K key, V value) {
3134 checkKey(key);
3135 return m.put(key, value);
3136 }
3137
3138 public V remove(Object key) {
3139 K k = (K)key;
3140 return (!inHalfOpenRange(k))? null : m.remove(k);
3141 }
3142
3143 public int size() {
3144 long count = 0;
3145 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3146 isBeforeEnd(n);
3147 n = n.next) {
3148 if (n.getValidValue() != null)
3149 ++count;
3150 }
3151 return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count;
3152 }
3153
3154 public boolean isEmpty() {
3155 return !isBeforeEnd(firstNode());
3156 }
3157
3158 public boolean containsValue(Object value) {
3159 if (value == null)
3160 throw new NullPointerException();
3161 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3162 isBeforeEnd(n);
3163 n = n.next) {
3164 V v = n.getValidValue();
3165 if (v != null && value.equals(v))
3166 return true;
3167 }
3168 return false;
3169 }
3170
3171 public void clear() {
3172 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3173 isBeforeEnd(n);
3174 n = n.next) {
3175 if (n.getValidValue() != null)
3176 m.remove(n.key);
3177 }
3178 }
3179
3180 /* ---------------- ConcurrentMap API methods -------------- */
3181
3182 public V putIfAbsent(K key, V value) {
3183 checkKey(key);
3184 return m.putIfAbsent(key, value);
3185 }
3186
3187 public boolean remove(Object key, Object value) {
3188 K k = (K)key;
3189 return inHalfOpenRange(k) && m.remove(k, value);
3190 }
3191
3192 public boolean replace(K key, V oldValue, V newValue) {
3193 checkKey(key);
3194 return m.replace(key, oldValue, newValue);
3195 }
3196
3197 public V replace(K key, V value) {
3198 checkKey(key);
3199 return m.replace(key, value);
3200 }
3201
3202 /* ---------------- SortedMap API methods -------------- */
3203
3204 public Comparator<? super K> comparator() {
3205 return m.comparator();
3206 }
3207
3208 public K firstKey() {
3209 ConcurrentSkipListMap.Node<K,V> n = firstNode();
3210 if (isBeforeEnd(n))
3211 return n.key;
3212 else
3213 throw new NoSuchElementException();
3214 }
3215
3216 public K lastKey() {
3217 ConcurrentSkipListMap.Node<K,V> n = lastNode();
3218 if (n != null) {
3219 K last = n.key;
3220 if (inHalfOpenRange(last))
3221 return last;
3222 }
3223 throw new NoSuchElementException();
3224 }
3225
3226 public ConcurrentNavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
3227 if (fromKey == null || toKey == null)
3228 throw new NullPointerException();
3229 if (!inOpenRange(fromKey) || !inOpenRange(toKey))
3230 throw new IllegalArgumentException("key out of range");
3231 return new ConcurrentSkipListSubMap(m, fromKey, toKey);
3232 }
3233
3234 public ConcurrentNavigableMap<K,V> navigableHeadMap(K toKey) {
3235 if (toKey == null)
3236 throw new NullPointerException();
3237 if (!inOpenRange(toKey))
3238 throw new IllegalArgumentException("key out of range");
3239 return new ConcurrentSkipListSubMap(m, least, toKey);
3240 }
3241
3242 public ConcurrentNavigableMap<K,V> navigableTailMap(K fromKey) {
3243 if (fromKey == null)
3244 throw new NullPointerException();
3245 if (!inOpenRange(fromKey))
3246 throw new IllegalArgumentException("key out of range");
3247 return new ConcurrentSkipListSubMap(m, fromKey, fence);
3248 }
3249
3250 public SortedMap<K,V> subMap(K fromKey, K toKey) {
3251 return navigableSubMap(fromKey, toKey);
3252 }
3253
3254 public SortedMap<K,V> headMap(K toKey) {
3255 return navigableHeadMap(toKey);
3256 }
3257
3258 public SortedMap<K,V> tailMap(K fromKey) {
3259 return navigableTailMap(fromKey);
3260 }
3261
3262 /* ---------------- Relational methods -------------- */
3263
3264 public Map.Entry<K,V> ceilingEntry(K key) {
3265 return (Map.Entry<K,V>)
3266 m.getNear(key, m.GT|m.EQ, least, fence, false);
3267 }
3268
3269 public K ceilingKey(K key) {
3270 return (K)
3271 m.getNear(key, m.GT|m.EQ, least, fence, true);
3272 }
3273
3274 public Map.Entry<K,V> lowerEntry(K key) {
3275 return (Map.Entry<K,V>)
3276 m.getNear(key, m.LT, least, fence, false);
3277 }
3278
3279 public K lowerKey(K key) {
3280 return (K)
3281 m.getNear(key, m.LT, least, fence, true);
3282 }
3283
3284 public Map.Entry<K,V> floorEntry(K key) {
3285 return (Map.Entry<K,V>)
3286 m.getNear(key, m.LT|m.EQ, least, fence, false);
3287 }
3288
3289 public K floorKey(K key) {
3290 return (K)
3291 m.getNear(key, m.LT|m.EQ, least, fence, true);
3292 }
3293
3294
3295 public Map.Entry<K,V> higherEntry(K key) {
3296 return (Map.Entry<K,V>)
3297 m.getNear(key, m.GT, least, fence, false);
3298 }
3299
3300 public K higherKey(K key) {
3301 return (K)
3302 m.getNear(key, m.GT, least, fence, true);
3303 }
3304
3305 public Map.Entry<K,V> firstEntry() {
3306 for (;;) {
3307 ConcurrentSkipListMap.Node<K,V> n = firstNode();
3308 if (!isBeforeEnd(n))
3309 return null;
3310 Map.Entry<K,V> e = n.createSnapshot();
3311 if (e != null)
3312 return e;
3313 }
3314 }
3315
3316 public Map.Entry<K,V> lastEntry() {
3317 for (;;) {
3318 ConcurrentSkipListMap.Node<K,V> n = lastNode();
3319 if (n == null || !inHalfOpenRange(n.key))
3320 return null;
3321 Map.Entry<K,V> e = n.createSnapshot();
3322 if (e != null)
3323 return e;
3324 }
3325 }
3326
3327 public Map.Entry<K,V> pollFirstEntry() {
3328 return (Map.Entry<K,V>)
3329 m.removeFirstEntryOfSubrange(least, fence, false);
3330 }
3331
3332 public Map.Entry<K,V> pollLastEntry() {
3333 return (Map.Entry<K,V>)
3334 m.removeLastEntryOfSubrange(least, fence, false);
3335 }
3336
3337 /* ---------------- Submap Views -------------- */
3338
3339 public Set<K> keySet() {
3340 Set<K> ks = keySetView;
3341 return (ks != null) ? ks : (keySetView = new KeySetView());
3342 }
3343
3344 class KeySetView extends AbstractSet<K> {
3345 public Iterator<K> iterator() {
3346 return m.subMapKeyIterator(least, fence);
3347 }
3348 public int size() {
3349 return ConcurrentSkipListSubMap.this.size();
3350 }
3351 public boolean isEmpty() {
3352 return ConcurrentSkipListSubMap.this.isEmpty();
3353 }
3354 public boolean contains(Object k) {
3355 return ConcurrentSkipListSubMap.this.containsKey(k);
3356 }
3357 public Object[] toArray() {
3358 Collection<K> c = new ArrayList<K>();
3359 for (Iterator<K> i = iterator(); i.hasNext(); )
3360 c.add(i.next());
3361 return c.toArray();
3362 }
3363 public <T> T[] toArray(T[] a) {
3364 Collection<K> c = new ArrayList<K>();
3365 for (Iterator<K> i = iterator(); i.hasNext(); )
3366 c.add(i.next());
3367 return c.toArray(a);
3368 }
3369 }
3370
3371 public Set<K> descendingKeySet() {
3372 Set<K> ks = descendingKeySetView;
3373 return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
3374 }
3375
3376 class DescendingKeySetView extends KeySetView {
3377 public Iterator<K> iterator() {
3378 return m.descendingSubMapKeyIterator(least, fence);
3379 }
3380 }
3381
3382 public Collection<V> values() {
3383 Collection<V> vs = valuesView;
3384 return (vs != null) ? vs : (valuesView = new ValuesView());
3385 }
3386
3387 class ValuesView extends AbstractCollection<V> {
3388 public Iterator<V> iterator() {
3389 return m.subMapValueIterator(least, fence);
3390 }
3391 public int size() {
3392 return ConcurrentSkipListSubMap.this.size();
3393 }
3394 public boolean isEmpty() {
3395 return ConcurrentSkipListSubMap.this.isEmpty();
3396 }
3397 public boolean contains(Object v) {
3398 return ConcurrentSkipListSubMap.this.containsValue(v);
3399 }
3400 public Object[] toArray() {
3401 Collection<V> c = new ArrayList<V>();
3402 for (Iterator<V> i = iterator(); i.hasNext(); )
3403 c.add(i.next());
3404 return c.toArray();
3405 }
3406 public <T> T[] toArray(T[] a) {
3407 Collection<V> c = new ArrayList<V>();
3408 for (Iterator<V> i = iterator(); i.hasNext(); )
3409 c.add(i.next());
3410 return c.toArray(a);
3411 }
3412 }
3413
3414 public Set<Map.Entry<K,V>> entrySet() {
3415 Set<Map.Entry<K,V>> es = entrySetView;
3416 return (es != null) ? es : (entrySetView = new EntrySetView());
3417 }
3418
3419 class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
3420 public Iterator<Map.Entry<K,V>> iterator() {
3421 return m.subMapEntryIterator(least, fence);
3422 }
3423 public int size() {
3424 return ConcurrentSkipListSubMap.this.size();
3425 }
3426 public boolean isEmpty() {
3427 return ConcurrentSkipListSubMap.this.isEmpty();
3428 }
3429 public boolean contains(Object o) {
3430 if (!(o instanceof Map.Entry))
3431 return false;
3432 Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3433 K key = e.getKey();
3434 if (!inHalfOpenRange(key))
3435 return false;
3436 V v = m.get(key);
3437 return v != null && v.equals(e.getValue());
3438 }
3439 public boolean remove(Object o) {
3440 if (!(o instanceof Map.Entry))
3441 return false;
3442 Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3443 K key = e.getKey();
3444 if (!inHalfOpenRange(key))
3445 return false;
3446 return m.remove(key, e.getValue());
3447 }
3448 public Object[] toArray() {
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();
3453 }
3454 public <T> T[] toArray(T[] a) {
3455 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3456 for (Map.Entry e : this)
3457 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3458 return c.toArray(a);
3459 }
3460 }
3461
3462 public Set<Map.Entry<K,V>> descendingEntrySet() {
3463 Set<Map.Entry<K,V>> es = descendingEntrySetView;
3464 return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
3465 }
3466
3467 class DescendingEntrySetView extends EntrySetView {
3468 public Iterator<Map.Entry<K,V>> iterator() {
3469 return m.descendingSubMapEntryIterator(least, fence);
3470 }
3471 }
3472 }
3473 }