ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.30
Committed: Sun May 29 14:02:26 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.29: +3 -11 lines
Log Message:
Code simplifications

File Contents

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