ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.1
Committed: Tue Dec 28 12:14:13 2004 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Log Message:
Prepare jsr166x classes for Mustang integration

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