ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.17
Committed: Mon May 2 18:36:04 2005 UTC (19 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.16: +4 -8 lines
Log Message:
improve rendering of whitespace around code examples

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