ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.34
Committed: Sun Jun 19 23:01:20 2005 UTC (18 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.33: +2 -1 lines
Log Message:
Clarify comment

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()) | 1; // ensure nonzero
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 findFirst, and findLast and their
730 * variants. 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 (see
895 * Pugh's "Skip List Cookbook", sec 3.4).
896 *
897 * This uses the simplest of the generators described in George
898 * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality
899 * generator but is acceptable here. Note that bits are checked
900 * by testing sign, which is a little faster than testing low bit.
901 */
902 private int randomLevel() {
903 int level = 0;
904 int r = randomSeed;
905 int x = r ^ (r << 13);
906 x ^= x >>> 17;
907 randomSeed = x ^ (x << 5);
908 if (r < 0) {
909 while ((r <<= 1) > 0)
910 ++level;
911 }
912 return level;
913 }
914
915 /**
916 * Creates and adds index nodes for the given node.
917 * @param z the node
918 * @param level the level of the index
919 */
920 private void insertIndex(Node<K,V> z, int level) {
921 HeadIndex<K,V> h = head;
922 int max = h.level;
923
924 if (level <= max) {
925 Index<K,V> idx = null;
926 for (int i = 1; i <= level; ++i)
927 idx = new Index<K,V>(z, idx, null);
928 addIndex(idx, h, level);
929
930 } else { // Add a new level
931 /*
932 * To reduce interference by other threads checking for
933 * empty levels in tryReduceLevel, new levels are added
934 * with initialized right pointers. Which in turn requires
935 * keeping levels in an array to access them while
936 * creating new head index nodes from the opposite
937 * direction.
938 */
939 level = max + 1;
940 Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
941 Index<K,V> idx = null;
942 for (int i = 1; i <= level; ++i)
943 idxs[i] = idx = new Index<K,V>(z, idx, null);
944
945 HeadIndex<K,V> oldh;
946 int k;
947 for (;;) {
948 oldh = head;
949 int oldLevel = oldh.level;
950 if (level <= oldLevel) { // lost race to add level
951 k = level;
952 break;
953 }
954 HeadIndex<K,V> newh = oldh;
955 Node<K,V> oldbase = oldh.node;
956 for (int j = oldLevel+1; j <= level; ++j)
957 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
958 if (casHead(oldh, newh)) {
959 k = oldLevel;
960 break;
961 }
962 }
963 addIndex(idxs[k], oldh, k);
964 }
965 }
966
967 /**
968 * Adds given index nodes from given level down to 1.
969 * @param idx the topmost index node being inserted
970 * @param h the value of head to use to insert. This must be
971 * snapshotted by callers to provide correct insertion level
972 * @param indexLevel the level of the index
973 */
974 private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
975 // Track next level to insert in case of retries
976 int insertionLevel = indexLevel;
977 Comparable<? super K> key = comparable(idx.key);
978
979 // Similar to findPredecessor, but adding index nodes along
980 // path to key.
981 for (;;) {
982 Index<K,V> q = h;
983 Index<K,V> t = idx;
984 int j = h.level;
985 for (;;) {
986 Index<K,V> r = q.right;
987 if (r != null) {
988 // compare before deletion check avoids needing recheck
989 int c = key.compareTo(r.key);
990 if (r.indexesDeletedNode()) {
991 if (q.unlink(r))
992 continue;
993 else
994 break;
995 }
996 if (c > 0) {
997 q = r;
998 continue;
999 }
1000 }
1001
1002 if (j == insertionLevel) {
1003 // Don't insert index if node already deleted
1004 if (t.indexesDeletedNode()) {
1005 findNode(key); // cleans up
1006 return;
1007 }
1008 if (!q.link(r, t))
1009 break; // restart
1010 if (--insertionLevel == 0) {
1011 // need final deletion check before return
1012 if (t.indexesDeletedNode())
1013 findNode(key);
1014 return;
1015 }
1016 }
1017
1018 if (j > insertionLevel && j <= indexLevel)
1019 t = t.down;
1020 q = q.down;
1021 --j;
1022 }
1023 }
1024 }
1025
1026 /* ---------------- Deletion -------------- */
1027
1028 /**
1029 * Main deletion method. Locates node, nulls value, appends a
1030 * deletion marker, unlinks predecessor, removes associated index
1031 * nodes, and possibly reduces head index level.
1032 *
1033 * Index nodes are cleared out simply by calling findPredecessor.
1034 * which unlinks indexes to deleted nodes found along path to key,
1035 * which will include the indexes to this node. This is done
1036 * unconditionally. We can't check beforehand whether there are
1037 * index nodes because it might be the case that some or all
1038 * indexes hadn't been inserted yet for this node during initial
1039 * search for it, and we'd like to ensure lack of garbage
1040 * retention, so must call to be sure.
1041 *
1042 * @param okey the key
1043 * @param value if non-null, the value that must be
1044 * associated with key
1045 * @return the node, or null if not found
1046 */
1047 private V doRemove(Object okey, Object value) {
1048 Comparable<? super K> key = comparable(okey);
1049 for (;;) {
1050 Node<K,V> b = findPredecessor(key);
1051 Node<K,V> n = b.next;
1052 for (;;) {
1053 if (n == null)
1054 return null;
1055 Node<K,V> f = n.next;
1056 if (n != b.next) // inconsistent read
1057 break;
1058 Object v = n.value;
1059 if (v == null) { // n is deleted
1060 n.helpDelete(b, f);
1061 break;
1062 }
1063 if (v == n || b.value == null) // b is deleted
1064 break;
1065 int c = key.compareTo(n.key);
1066 if (c < 0)
1067 return null;
1068 if (c > 0) {
1069 b = n;
1070 n = f;
1071 continue;
1072 }
1073 if (value != null && !value.equals(v))
1074 return null;
1075 if (!n.casValue(v, null))
1076 break;
1077 if (!n.appendMarker(f) || !b.casNext(n, f))
1078 findNode(key); // Retry via findNode
1079 else {
1080 findPredecessor(key); // Clean index
1081 if (head.right == null)
1082 tryReduceLevel();
1083 }
1084 return (V)v;
1085 }
1086 }
1087 }
1088
1089 /**
1090 * Possibly reduce head level if it has no nodes. This method can
1091 * (rarely) make mistakes, in which case levels can disappear even
1092 * though they are about to contain index nodes. This impacts
1093 * performance, not correctness. To minimize mistakes as well as
1094 * to reduce hysteresis, the level is reduced by one only if the
1095 * topmost three levels look empty. Also, if the removed level
1096 * looks non-empty after CAS, we try to change it back quick
1097 * before anyone notices our mistake! (This trick works pretty
1098 * well because this method will practically never make mistakes
1099 * unless current thread stalls immediately before first CAS, in
1100 * which case it is very unlikely to stall again immediately
1101 * afterwards, so will recover.)
1102 *
1103 * We put up with all this rather than just let levels grow
1104 * because otherwise, even a small map that has undergone a large
1105 * number of insertions and removals will have a lot of levels,
1106 * slowing down access more than would an occasional unwanted
1107 * reduction.
1108 */
1109 private void tryReduceLevel() {
1110 HeadIndex<K,V> h = head;
1111 HeadIndex<K,V> d;
1112 HeadIndex<K,V> e;
1113 if (h.level > 3 &&
1114 (d = (HeadIndex<K,V>)h.down) != null &&
1115 (e = (HeadIndex<K,V>)d.down) != null &&
1116 e.right == null &&
1117 d.right == null &&
1118 h.right == null &&
1119 casHead(h, d) && // try to set
1120 h.right != null) // recheck
1121 casHead(d, h); // try to backout
1122 }
1123
1124 /**
1125 * Version of remove with boolean return. Needed by view classes
1126 */
1127 boolean removep(Object key) {
1128 return doRemove(key, null) != null;
1129 }
1130
1131 /* ---------------- Finding and removing first element -------------- */
1132
1133 /**
1134 * Specialized variant of findNode to get first valid node.
1135 * @return first node or null if empty
1136 */
1137 Node<K,V> findFirst() {
1138 for (;;) {
1139 Node<K,V> b = head.node;
1140 Node<K,V> n = b.next;
1141 if (n == null)
1142 return null;
1143 if (n.value != null)
1144 return n;
1145 n.helpDelete(b, n.next);
1146 }
1147 }
1148
1149 /**
1150 * Removes first entry; returns its key. Note: The
1151 * mostly-redundant methods for removing first and last keys vs
1152 * entries exist to avoid needless creation of Entry nodes when
1153 * only the key is needed. The minor reduction in overhead is
1154 * worth the minor code duplication.
1155 * @return null if empty, else key of first entry
1156 */
1157 K pollFirstKey() {
1158 for (;;) {
1159 Node<K,V> b = head.node;
1160 Node<K,V> n = b.next;
1161 if (n == null)
1162 return null;
1163 Node<K,V> f = n.next;
1164 if (n != b.next)
1165 continue;
1166 Object v = n.value;
1167 if (v == null) {
1168 n.helpDelete(b, f);
1169 continue;
1170 }
1171 if (!n.casValue(v, null))
1172 continue;
1173 if (!n.appendMarker(f) || !b.casNext(n, f))
1174 findFirst(); // retry
1175 clearIndexToFirst();
1176 return n.key;
1177 }
1178 }
1179
1180 /**
1181 * Removes first entry; returns its snapshot.
1182 * @return null if empty, else snapshot of first entry
1183 */
1184 Map.Entry<K,V> doRemoveFirstEntry() {
1185 for (;;) {
1186 Node<K,V> b = head.node;
1187 Node<K,V> n = b.next;
1188 if (n == null)
1189 return null;
1190 Node<K,V> f = n.next;
1191 if (n != b.next)
1192 continue;
1193 Object v = n.value;
1194 if (v == null) {
1195 n.helpDelete(b, f);
1196 continue;
1197 }
1198 if (!n.casValue(v, null))
1199 continue;
1200 if (!n.appendMarker(f) || !b.casNext(n, f))
1201 findFirst(); // retry
1202 clearIndexToFirst();
1203 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
1204 }
1205 }
1206
1207 /**
1208 * Clears out index nodes associated with deleted first entry.
1209 */
1210 private void clearIndexToFirst() {
1211 for (;;) {
1212 Index<K,V> q = head;
1213 for (;;) {
1214 Index<K,V> r = q.right;
1215 if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1216 break;
1217 if ((q = q.down) == null) {
1218 if (head.right == null)
1219 tryReduceLevel();
1220 return;
1221 }
1222 }
1223 }
1224 }
1225
1226
1227 /* ---------------- Finding and removing last element -------------- */
1228
1229 /**
1230 * Specialized version of find to get last valid node.
1231 * @return last node or null if empty
1232 */
1233 Node<K,V> findLast() {
1234 /*
1235 * findPredecessor can't be used to traverse index level
1236 * because this doesn't use comparisons. So traversals of
1237 * both levels are folded together.
1238 */
1239 Index<K,V> q = head;
1240 for (;;) {
1241 Index<K,V> d, r;
1242 if ((r = q.right) != null) {
1243 if (r.indexesDeletedNode()) {
1244 q.unlink(r);
1245 q = head; // restart
1246 }
1247 else
1248 q = r;
1249 } else if ((d = q.down) != null) {
1250 q = d;
1251 } else {
1252 Node<K,V> b = q.node;
1253 Node<K,V> n = b.next;
1254 for (;;) {
1255 if (n == null)
1256 return (b.isBaseHeader())? null : b;
1257 Node<K,V> f = n.next; // inconsistent read
1258 if (n != b.next)
1259 break;
1260 Object v = n.value;
1261 if (v == null) { // n is deleted
1262 n.helpDelete(b, f);
1263 break;
1264 }
1265 if (v == n || b.value == null) // b is deleted
1266 break;
1267 b = n;
1268 n = f;
1269 }
1270 q = head; // restart
1271 }
1272 }
1273 }
1274
1275 /**
1276 * Specialized variant of findPredecessor to get predecessor of last
1277 * valid node. Needed when removing the last entry. It is possible
1278 * that all successors of returned node will have been deleted upon
1279 * return, in which case this method can be retried.
1280 * @return likely predecessor of last node
1281 */
1282 private Node<K,V> findPredecessorOfLast() {
1283 for (;;) {
1284 Index<K,V> q = head;
1285 for (;;) {
1286 Index<K,V> d, r;
1287 if ((r = q.right) != null) {
1288 if (r.indexesDeletedNode()) {
1289 q.unlink(r);
1290 break; // must restart
1291 }
1292 // proceed as far across as possible without overshooting
1293 if (r.node.next != null) {
1294 q = r;
1295 continue;
1296 }
1297 }
1298 if ((d = q.down) != null)
1299 q = d;
1300 else
1301 return q.node;
1302 }
1303 }
1304 }
1305
1306 /**
1307 * Removes last entry; returns key or null if empty.
1308 * @return null if empty, else key of last entry
1309 */
1310 K pollLastKey() {
1311 for (;;) {
1312 Node<K,V> b = findPredecessorOfLast();
1313 Node<K,V> n = b.next;
1314 if (n == null) {
1315 if (b.isBaseHeader()) // empty
1316 return null;
1317 else
1318 continue; // all b's successors are deleted; retry
1319 }
1320 for (;;) {
1321 Node<K,V> f = n.next;
1322 if (n != b.next) // inconsistent read
1323 break;
1324 Object v = n.value;
1325 if (v == null) { // n is deleted
1326 n.helpDelete(b, f);
1327 break;
1328 }
1329 if (v == n || b.value == null) // b is deleted
1330 break;
1331 if (f != null) {
1332 b = n;
1333 n = f;
1334 continue;
1335 }
1336 if (!n.casValue(v, null))
1337 break;
1338 K key = n.key;
1339 Comparable<? super K> ck = comparable(key);
1340 if (!n.appendMarker(f) || !b.casNext(n, f))
1341 findNode(ck); // Retry via findNode
1342 else {
1343 findPredecessor(ck); // Clean index
1344 if (head.right == null)
1345 tryReduceLevel();
1346 }
1347 return key;
1348 }
1349 }
1350 }
1351
1352 /**
1353 * Removes last entry; returns its snapshot.
1354 * Specialized variant of doRemove.
1355 * @return null if empty, else snapshot of last entry
1356 */
1357 Map.Entry<K,V> doRemoveLastEntry() {
1358 for (;;) {
1359 Node<K,V> b = findPredecessorOfLast();
1360 Node<K,V> n = b.next;
1361 if (n == null) {
1362 if (b.isBaseHeader()) // empty
1363 return null;
1364 else
1365 continue; // all b's successors are deleted; retry
1366 }
1367 for (;;) {
1368 Node<K,V> f = n.next;
1369 if (n != b.next) // inconsistent read
1370 break;
1371 Object v = n.value;
1372 if (v == null) { // n is deleted
1373 n.helpDelete(b, f);
1374 break;
1375 }
1376 if (v == n || b.value == null) // b is deleted
1377 break;
1378 if (f != null) {
1379 b = n;
1380 n = f;
1381 continue;
1382 }
1383 if (!n.casValue(v, null))
1384 break;
1385 K key = n.key;
1386 Comparable<? super K> ck = comparable(key);
1387 if (!n.appendMarker(f) || !b.casNext(n, f))
1388 findNode(ck); // Retry via findNode
1389 else {
1390 findPredecessor(ck); // Clean index
1391 if (head.right == null)
1392 tryReduceLevel();
1393 }
1394 return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1395 }
1396 }
1397 }
1398
1399 /* ---------------- Relational operations -------------- */
1400
1401 // Control values OR'ed as arguments to findNear
1402
1403 private static final int EQ = 1;
1404 private static final int LT = 2;
1405 private static final int GT = 0; // Actually checked as !LT
1406
1407 /**
1408 * Utility for ceiling, floor, lower, higher methods.
1409 * @param kkey the key
1410 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1411 * @return nearest node fitting relation, or null if no such
1412 */
1413 Node<K,V> findNear(K kkey, int rel) {
1414 Comparable<? super K> key = comparable(kkey);
1415 for (;;) {
1416 Node<K,V> b = findPredecessor(key);
1417 Node<K,V> n = b.next;
1418 for (;;) {
1419 if (n == null)
1420 return ((rel & LT) == 0 || b.isBaseHeader())? null : b;
1421 Node<K,V> f = n.next;
1422 if (n != b.next) // inconsistent read
1423 break;
1424 Object v = n.value;
1425 if (v == null) { // n is deleted
1426 n.helpDelete(b, f);
1427 break;
1428 }
1429 if (v == n || b.value == null) // b is deleted
1430 break;
1431 int c = key.compareTo(n.key);
1432 if ((c == 0 && (rel & EQ) != 0) ||
1433 (c < 0 && (rel & LT) == 0))
1434 return n;
1435 if ( c <= 0 && (rel & LT) != 0)
1436 return (b.isBaseHeader())? null : b;
1437 b = n;
1438 n = f;
1439 }
1440 }
1441 }
1442
1443 /**
1444 * Returns SimpleImmutableEntry for results of findNear.
1445 * @param kkey the key
1446 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1447 * @return Entry fitting relation, or null if no such
1448 */
1449 AbstractMap.SimpleImmutableEntry<K,V> getNear(K kkey, int rel) {
1450 for (;;) {
1451 Node<K,V> n = findNear(kkey, rel);
1452 if (n == null)
1453 return null;
1454 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1455 if (e != null)
1456 return e;
1457 }
1458 }
1459
1460 /**
1461 * Returns ceiling, or first node if key is <tt>null</tt>.
1462 */
1463 Node<K,V> findCeiling(K key) {
1464 return (key == null)? findFirst() : findNear(key, GT|EQ);
1465 }
1466
1467 /**
1468 * Returns lower node, or last node if key is <tt>null</tt>.
1469 */
1470 Node<K,V> findLower(K key) {
1471 return (key == null)? findLast() : findNear(key, LT);
1472 }
1473
1474 /**
1475 * Returns key for results of findNear after screening to ensure
1476 * result is in given range. Needed by submaps.
1477 * @param kkey the key
1478 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1479 * @param least minimum allowed key value
1480 * @param fence key greater than maximum allowed key value
1481 * @return Key fitting relation, or <tt>null</tt> if no such
1482 */
1483 K getNearKey(K kkey, int rel, K least, K fence) {
1484 K key = kkey;
1485 // Don't return keys less than least
1486 if ((rel & LT) == 0) {
1487 if (compare(key, least) < 0) {
1488 key = least;
1489 rel = rel | EQ;
1490 }
1491 }
1492
1493 for (;;) {
1494 Node<K,V> n = findNear(key, rel);
1495 if (n == null || !inHalfOpenRange(n.key, least, fence))
1496 return null;
1497 K k = n.key;
1498 V v = n.getValidValue();
1499 if (v != null)
1500 return k;
1501 }
1502 }
1503
1504
1505 /**
1506 * Returns SimpleImmutableEntry for results of findNear after
1507 * screening to ensure result is in given range. Needed by
1508 * submaps.
1509 * @param kkey the key
1510 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1511 * @param least minimum allowed key value
1512 * @param fence key greater than maximum allowed key value
1513 * @return Entry fitting relation, or <tt>null</tt> if no such
1514 */
1515 Map.Entry<K,V> getNearEntry(K kkey, int rel, K least, K fence) {
1516 K key = kkey;
1517 // Don't return keys less than least
1518 if ((rel & LT) == 0) {
1519 if (compare(key, least) < 0) {
1520 key = least;
1521 rel = rel | EQ;
1522 }
1523 }
1524
1525 for (;;) {
1526 Node<K,V> n = findNear(key, rel);
1527 if (n == null || !inHalfOpenRange(n.key, least, fence))
1528 return null;
1529 K k = n.key;
1530 V v = n.getValidValue();
1531 if (v != null)
1532 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1533 }
1534 }
1535
1536 /**
1537 * Finds and removes least element of subrange.
1538 * @param least minimum allowed key value
1539 * @param fence key greater than maximum allowed key value
1540 * @return least Entry, or <tt>null</tt> if no such
1541 */
1542 Map.Entry<K,V> removeFirstEntryOfSubrange(K least, K fence) {
1543 for (;;) {
1544 Node<K,V> n = findCeiling(least);
1545 if (n == null)
1546 return null;
1547 K k = n.key;
1548 if (fence != null && compare(k, fence) >= 0)
1549 return null;
1550 V v = doRemove(k, null);
1551 if (v != null)
1552 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1553 }
1554 }
1555
1556 /**
1557 * Finds and removes greatest element of subrange.
1558 * @param least minimum allowed key value
1559 * @param fence key greater than maximum allowed key value
1560 * @return least Entry, or <tt>null</tt> if no such
1561 */
1562 Map.Entry<K,V> removeLastEntryOfSubrange(K least, K fence) {
1563 for (;;) {
1564 Node<K,V> n = findLower(fence);
1565 if (n == null)
1566 return null;
1567 K k = n.key;
1568 if (least != null && compare(k, least) < 0)
1569 return null;
1570 V v = doRemove(k, null);
1571 if (v != null)
1572 return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1573 }
1574 }
1575
1576
1577
1578 /* ---------------- Constructors -------------- */
1579
1580 /**
1581 * Constructs a new, empty map, sorted according to the
1582 * {@linkplain Comparable natural ordering} of the keys.
1583 */
1584 public ConcurrentSkipListMap() {
1585 this.comparator = null;
1586 initialize();
1587 }
1588
1589 /**
1590 * Constructs a new, empty map, sorted according to the specified
1591 * comparator.
1592 *
1593 * @param comparator the comparator that will be used to order this map.
1594 * If <tt>null</tt>, the {@linkplain Comparable natural
1595 * ordering} of the keys will be used.
1596 */
1597 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1598 this.comparator = comparator;
1599 initialize();
1600 }
1601
1602 /**
1603 * Constructs a new map containing the same mappings as the given map,
1604 * sorted according to the {@linkplain Comparable natural ordering} of
1605 * the keys.
1606 *
1607 * @param m the map whose mappings are to be placed in this map
1608 * @throws ClassCastException if the keys in <tt>m</tt> are not
1609 * {@link Comparable}, or are not mutually comparable
1610 * @throws NullPointerException if the specified map or any of its keys
1611 * or values are null
1612 */
1613 public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1614 this.comparator = null;
1615 initialize();
1616 putAll(m);
1617 }
1618
1619 /**
1620 * Constructs a new map containing the same mappings and using the
1621 * same ordering as the specified sorted map.
1622 *
1623 * @param m the sorted map whose mappings are to be placed in this
1624 * map, and whose comparator is to be used to sort this map
1625 * @throws NullPointerException if the specified sorted map or any of
1626 * its keys or values are null
1627 */
1628 public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1629 this.comparator = m.comparator();
1630 initialize();
1631 buildFromSorted(m);
1632 }
1633
1634 /**
1635 * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
1636 * instance. (The keys and values themselves are not cloned.)
1637 *
1638 * @return a shallow copy of this map
1639 */
1640 public ConcurrentSkipListMap<K,V> clone() {
1641 ConcurrentSkipListMap<K,V> clone = null;
1642 try {
1643 clone = (ConcurrentSkipListMap<K,V>) super.clone();
1644 } catch (CloneNotSupportedException e) {
1645 throw new InternalError();
1646 }
1647
1648 clone.initialize();
1649 clone.buildFromSorted(this);
1650 return clone;
1651 }
1652
1653 /**
1654 * Streamlined bulk insertion to initialize from elements of
1655 * given sorted map. Call only from constructor or clone
1656 * method.
1657 */
1658 private void buildFromSorted(SortedMap<K, ? extends V> map) {
1659 if (map == null)
1660 throw new NullPointerException();
1661
1662 HeadIndex<K,V> h = head;
1663 Node<K,V> basepred = h.node;
1664
1665 // Track the current rightmost node at each level. Uses an
1666 // ArrayList to avoid committing to initial or maximum level.
1667 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1668
1669 // initialize
1670 for (int i = 0; i <= h.level; ++i)
1671 preds.add(null);
1672 Index<K,V> q = h;
1673 for (int i = h.level; i > 0; --i) {
1674 preds.set(i, q);
1675 q = q.down;
1676 }
1677
1678 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1679 map.entrySet().iterator();
1680 while (it.hasNext()) {
1681 Map.Entry<? extends K, ? extends V> e = it.next();
1682 int j = randomLevel();
1683 if (j > h.level) j = h.level + 1;
1684 K k = e.getKey();
1685 V v = e.getValue();
1686 if (k == null || v == null)
1687 throw new NullPointerException();
1688 Node<K,V> z = new Node<K,V>(k, v, null);
1689 basepred.next = z;
1690 basepred = z;
1691 if (j > 0) {
1692 Index<K,V> idx = null;
1693 for (int i = 1; i <= j; ++i) {
1694 idx = new Index<K,V>(z, idx, null);
1695 if (i > h.level)
1696 h = new HeadIndex<K,V>(h.node, h, idx, i);
1697
1698 if (i < preds.size()) {
1699 preds.get(i).right = idx;
1700 preds.set(i, idx);
1701 } else
1702 preds.add(idx);
1703 }
1704 }
1705 }
1706 head = h;
1707 }
1708
1709 /* ---------------- Serialization -------------- */
1710
1711 /**
1712 * Save the state of this map to a stream.
1713 *
1714 * @serialData The key (Object) and value (Object) for each
1715 * key-value mapping represented by the map, followed by
1716 * <tt>null</tt>. The key-value mappings are emitted in key-order
1717 * (as determined by the Comparator, or by the keys' natural
1718 * ordering if no Comparator).
1719 */
1720 private void writeObject(java.io.ObjectOutputStream s)
1721 throws java.io.IOException {
1722 // Write out the Comparator and any hidden stuff
1723 s.defaultWriteObject();
1724
1725 // Write out keys and values (alternating)
1726 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1727 V v = n.getValidValue();
1728 if (v != null) {
1729 s.writeObject(n.key);
1730 s.writeObject(v);
1731 }
1732 }
1733 s.writeObject(null);
1734 }
1735
1736 /**
1737 * Reconstitute the map from a stream.
1738 */
1739 private void readObject(final java.io.ObjectInputStream s)
1740 throws java.io.IOException, ClassNotFoundException {
1741 // Read in the Comparator and any hidden stuff
1742 s.defaultReadObject();
1743 // Reset transients
1744 initialize();
1745
1746 /*
1747 * This is nearly identical to buildFromSorted, but is
1748 * distinct because readObject calls can't be nicely adapted
1749 * as the kind of iterator needed by buildFromSorted. (They
1750 * can be, but doing so requires type cheats and/or creation
1751 * of adaptor classes.) It is simpler to just adapt the code.
1752 */
1753
1754 HeadIndex<K,V> h = head;
1755 Node<K,V> basepred = h.node;
1756 ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1757 for (int i = 0; i <= h.level; ++i)
1758 preds.add(null);
1759 Index<K,V> q = h;
1760 for (int i = h.level; i > 0; --i) {
1761 preds.set(i, q);
1762 q = q.down;
1763 }
1764
1765 for (;;) {
1766 Object k = s.readObject();
1767 if (k == null)
1768 break;
1769 Object v = s.readObject();
1770 if (v == null)
1771 throw new NullPointerException();
1772 K key = (K) k;
1773 V val = (V) v;
1774 int j = randomLevel();
1775 if (j > h.level) j = h.level + 1;
1776 Node<K,V> z = new Node<K,V>(key, val, null);
1777 basepred.next = z;
1778 basepred = z;
1779 if (j > 0) {
1780 Index<K,V> idx = null;
1781 for (int i = 1; i <= j; ++i) {
1782 idx = new Index<K,V>(z, idx, null);
1783 if (i > h.level)
1784 h = new HeadIndex<K,V>(h.node, h, idx, i);
1785
1786 if (i < preds.size()) {
1787 preds.get(i).right = idx;
1788 preds.set(i, idx);
1789 } else
1790 preds.add(idx);
1791 }
1792 }
1793 }
1794 head = h;
1795 }
1796
1797 /* ------ Map API methods ------ */
1798
1799 /**
1800 * Returns <tt>true</tt> if this map contains a mapping for the specified
1801 * key.
1802 *
1803 * @param key key whose presence in this map is to be tested
1804 * @return <tt>true</tt> if this map contains a mapping for the specified key
1805 * @throws ClassCastException if the specified key cannot be compared
1806 * with the keys currently in the map
1807 * @throws NullPointerException if the specified key is null
1808 */
1809 public boolean containsKey(Object key) {
1810 return doGet(key) != null;
1811 }
1812
1813 /**
1814 * Returns the value to which this map maps the specified key, or
1815 * <tt>null</tt> if the map contains no mapping for the key.
1816 *
1817 * @param key key whose associated value is to be returned
1818 * @return the value to which this map maps the specified key, or
1819 * <tt>null</tt> if the map contains no mapping for the key
1820 * @throws ClassCastException if the specified key cannot be compared
1821 * with the keys currently in the map
1822 * @throws NullPointerException if the specified key is null
1823 */
1824 public V get(Object key) {
1825 return doGet(key);
1826 }
1827
1828 /**
1829 * Associates the specified value with the specified key in this map.
1830 * If the map previously contained a mapping for the key, the old
1831 * value is replaced.
1832 *
1833 * @param key key with which the specified value is to be associated
1834 * @param value value to be associated with the specified key
1835 * @return the previous value associated with the specified key, or
1836 * <tt>null</tt> if there was no mapping for the key
1837 * @throws ClassCastException if the specified key cannot be compared
1838 * with the keys currently in the map
1839 * @throws NullPointerException if the specified key or value is null
1840 */
1841 public V put(K key, V value) {
1842 if (value == null)
1843 throw new NullPointerException();
1844 return doPut(key, value, false);
1845 }
1846
1847 /**
1848 * Removes the mapping for this key from this map if present.
1849 *
1850 * @param key key for which mapping should be removed
1851 * @return the previous value associated with the specified key, or
1852 * <tt>null</tt> if there was no mapping for the key
1853 * @throws ClassCastException if the specified key cannot be compared
1854 * with the keys currently in the map
1855 * @throws NullPointerException if the specified key is null
1856 */
1857 public V remove(Object key) {
1858 return doRemove(key, null);
1859 }
1860
1861 /**
1862 * Returns <tt>true</tt> if this map maps one or more keys to the
1863 * specified value. This operation requires time linear in the
1864 * map size.
1865 *
1866 * @param value value whose presence in this map is to be tested
1867 * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1868 * <tt>false</tt> otherwise
1869 * @throws NullPointerException if the specified value is null
1870 */
1871 public boolean containsValue(Object value) {
1872 if (value == null)
1873 throw new NullPointerException();
1874 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1875 V v = n.getValidValue();
1876 if (v != null && value.equals(v))
1877 return true;
1878 }
1879 return false;
1880 }
1881
1882 /**
1883 * Returns the number of key-value mappings in this map. If this map
1884 * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1885 * returns <tt>Integer.MAX_VALUE</tt>.
1886 *
1887 * <p>Beware that, unlike in most collections, this method is
1888 * <em>NOT</em> a constant-time operation. Because of the
1889 * asynchronous nature of these maps, determining the current
1890 * number of elements requires traversing them all to count them.
1891 * Additionally, it is possible for the size to change during
1892 * execution of this method, in which case the returned result
1893 * will be inaccurate. Thus, this method is typically not very
1894 * useful in concurrent applications.
1895 *
1896 * @return the number of elements in this map
1897 */
1898 public int size() {
1899 long count = 0;
1900 for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1901 if (n.getValidValue() != null)
1902 ++count;
1903 }
1904 return (count >= Integer.MAX_VALUE)? Integer.MAX_VALUE : (int)count;
1905 }
1906
1907 /**
1908 * Returns <tt>true</tt> if this map contains no key-value mappings.
1909 * @return <tt>true</tt> if this map contains no key-value mappings
1910 */
1911 public boolean isEmpty() {
1912 return findFirst() == null;
1913 }
1914
1915 /**
1916 * Removes all of the mappings from this map.
1917 */
1918 public void clear() {
1919 initialize();
1920 }
1921
1922 /**
1923 * Returns a {@link Set} view of the keys contained in this map.
1924 * The set's iterator returns the keys in ascending order.
1925 * The set is backed by the map, so changes to the map are
1926 * reflected in the set, and vice-versa. The set supports element
1927 * removal, which removes the corresponding mapping from the map,
1928 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1929 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1930 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
1931 * operations.
1932 *
1933 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1934 * that will never throw {@link ConcurrentModificationException},
1935 * and guarantees to traverse elements as they existed upon
1936 * construction of the iterator, and may (but is not guaranteed to)
1937 * reflect any modifications subsequent to construction.
1938 *
1939 * @return a set view of the keys contained in this map, sorted in
1940 * ascending order
1941 */
1942 public Set<K> keySet() {
1943 /*
1944 * Note: Lazy initialization works here and for other views
1945 * because view classes are stateless/immutable so it doesn't
1946 * matter wrt correctness if more than one is created (which
1947 * will only rarely happen). Even so, the following idiom
1948 * conservatively ensures that the method returns the one it
1949 * created if it does so, not one created by another racing
1950 * thread.
1951 */
1952 KeySet ks = keySet;
1953 return (ks != null) ? ks : (keySet = new KeySet());
1954 }
1955
1956 /**
1957 * Returns a {@link Set} view of the keys contained in this map.
1958 * The set's iterator returns the keys in descending order.
1959 * The set is backed by the map, so changes to the map are
1960 * reflected in the set, and vice-versa. The set supports element
1961 * removal, which removes the corresponding mapping from the map,
1962 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1963 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1964 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
1965 * operations.
1966 *
1967 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1968 * that will never throw {@link ConcurrentModificationException},
1969 * and guarantees to traverse elements as they existed upon
1970 * construction of the iterator, and may (but is not guaranteed to)
1971 * reflect any modifications subsequent to construction.
1972 */
1973 public Set<K> descendingKeySet() {
1974 /*
1975 * Note: Lazy initialization works here and for other views
1976 * because view classes are stateless/immutable so it doesn't
1977 * matter wrt correctness if more than one is created (which
1978 * will only rarely happen). Even so, the following idiom
1979 * conservatively ensures that the method returns the one it
1980 * created if it does so, not one created by another racing
1981 * thread.
1982 */
1983 DescendingKeySet ks = descendingKeySet;
1984 return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1985 }
1986
1987 /**
1988 * Returns a {@link Collection} view of the values contained in this map.
1989 * The collection's iterator returns the values in ascending order
1990 * of the corresponding keys.
1991 * The collection is backed by the map, so changes to the map are
1992 * reflected in the collection, and vice-versa. The collection
1993 * supports element removal, which removes the corresponding
1994 * mapping from the map, via the <tt>Iterator.remove</tt>,
1995 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1996 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1997 * support the <tt>add</tt> or <tt>addAll</tt> operations.
1998 *
1999 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2000 * that will never throw {@link ConcurrentModificationException},
2001 * and guarantees to traverse elements as they existed upon
2002 * construction of the iterator, and may (but is not guaranteed to)
2003 * reflect any modifications subsequent to construction.
2004 */
2005 public Collection<V> values() {
2006 Values vs = values;
2007 return (vs != null) ? vs : (values = new Values());
2008 }
2009
2010 /**
2011 * Returns a {@link Set} view of the mappings contained in this map.
2012 * The set's iterator returns the entries in ascending key order.
2013 * The set is backed by the map, so changes to the map are
2014 * reflected in the set, and vice-versa. The set supports element
2015 * removal, which removes the corresponding mapping from the map,
2016 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
2017 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
2018 * operations. It does not support the <tt>add</tt> or
2019 * <tt>addAll</tt> operations.
2020 *
2021 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2022 * that will never throw {@link ConcurrentModificationException},
2023 * and guarantees to traverse elements as they existed upon
2024 * construction of the iterator, and may (but is not guaranteed to)
2025 * reflect any modifications subsequent to construction.
2026 *
2027 * <p>The <tt>Map.Entry</tt> elements returned by
2028 * <tt>iterator.next()</tt> do <em>not</em> support the
2029 * <tt>setValue</tt> operation.
2030 *
2031 * @return a set view of the mappings contained in this map,
2032 * sorted in ascending key order
2033 */
2034 public Set<Map.Entry<K,V>> entrySet() {
2035 EntrySet es = entrySet;
2036 return (es != null) ? es : (entrySet = new EntrySet());
2037 }
2038
2039 /**
2040 * Returns a {@link Set} view of the mappings contained in this map.
2041 * The set's iterator returns the entries in descending key order.
2042 * The set is backed by the map, so changes to the map are
2043 * reflected in the set, and vice-versa. The set supports element
2044 * removal, which removes the corresponding mapping from the map,
2045 * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
2046 * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
2047 * operations. It does not support the <tt>add</tt> or
2048 * <tt>addAll</tt> operations.
2049 *
2050 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
2051 * that will never throw {@link ConcurrentModificationException},
2052 * and guarantees to traverse elements as they existed upon
2053 * construction of the iterator, and may (but is not guaranteed to)
2054 * reflect any modifications subsequent to construction.
2055 *
2056 * <p>The <tt>Map.Entry</tt> elements returned by
2057 * <tt>iterator.next()</tt> do <em>not</em> support the
2058 * <tt>setValue</tt> operation.
2059 */
2060 public Set<Map.Entry<K,V>> descendingEntrySet() {
2061 DescendingEntrySet es = descendingEntrySet;
2062 return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
2063 }
2064
2065 /* ---------------- AbstractMap Overrides -------------- */
2066
2067 /**
2068 * Compares the specified object with this map for equality.
2069 * Returns <tt>true</tt> if the given object is also a map and the
2070 * two maps represent the same mappings. More formally, two maps
2071 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
2072 * <tt>m1.keySet().equals(m2.keySet())</tt> and for every key
2073 * <tt>k</tt> in <tt>m1.keySet()</tt>, <tt> (m1.get(k)==null ?
2074 * m2.get(k)==null : m1.get(k).equals(m2.get(k))) </tt>. This
2075 * operation may return misleading results if either map is
2076 * concurrently modified during execution of this method.
2077 *
2078 * @param o object to be compared for equality with this map
2079 * @return <tt>true</tt> if the specified object is equal to this map
2080 */
2081 public boolean equals(Object o) {
2082 if (o == this)
2083 return true;
2084 if (!(o instanceof Map))
2085 return false;
2086 Map<?,?> m = (Map<?,?>) o;
2087 try {
2088 for (Map.Entry<K,V> e : this.entrySet())
2089 if (! e.getValue().equals(m.get(e.getKey())))
2090 return false;
2091 for (Map.Entry<?,?> e : m.entrySet()) {
2092 Object k = e.getKey();
2093 Object v = e.getValue();
2094 if (k == null || v == null || !v.equals(get(k)))
2095 return false;
2096 }
2097 return true;
2098 } catch (ClassCastException unused) {
2099 return false;
2100 } catch (NullPointerException unused) {
2101 return false;
2102 }
2103 }
2104
2105 /* ------ ConcurrentMap API methods ------ */
2106
2107 /**
2108 * {@inheritDoc}
2109 *
2110 * @return the previous value associated with the specified key,
2111 * or <tt>null</tt> if there was no mapping for the key
2112 * @throws ClassCastException if the specified key cannot be compared
2113 * with the keys currently in the map
2114 * @throws NullPointerException if the specified key or value is null
2115 */
2116 public V putIfAbsent(K key, V value) {
2117 if (value == null)
2118 throw new NullPointerException();
2119 return doPut(key, value, true);
2120 }
2121
2122 /**
2123 * {@inheritDoc}
2124 *
2125 * @throws ClassCastException if the specified key cannot be compared
2126 * with the keys currently in the map
2127 * @throws NullPointerException if the specified key is null
2128 */
2129 public boolean remove(Object key, Object value) {
2130 if (value == null)
2131 return false;
2132 return doRemove(key, value) != null;
2133 }
2134
2135 /**
2136 * {@inheritDoc}
2137 *
2138 * @throws ClassCastException if the specified key cannot be compared
2139 * with the keys currently in the map
2140 * @throws NullPointerException if any of the arguments are null
2141 */
2142 public boolean replace(K key, V oldValue, V newValue) {
2143 if (oldValue == null || newValue == null)
2144 throw new NullPointerException();
2145 Comparable<? super K> k = comparable(key);
2146 for (;;) {
2147 Node<K,V> n = findNode(k);
2148 if (n == null)
2149 return false;
2150 Object v = n.value;
2151 if (v != null) {
2152 if (!oldValue.equals(v))
2153 return false;
2154 if (n.casValue(v, newValue))
2155 return true;
2156 }
2157 }
2158 }
2159
2160 /**
2161 * {@inheritDoc}
2162 *
2163 * @return the previous value associated with the specified key,
2164 * or <tt>null</tt> if there was no mapping for the key
2165 * @throws ClassCastException if the specified key cannot be compared
2166 * with the keys currently in the map
2167 * @throws NullPointerException if the specified key or value is null
2168 */
2169 public V replace(K key, V value) {
2170 if (value == null)
2171 throw new NullPointerException();
2172 Comparable<? super K> k = comparable(key);
2173 for (;;) {
2174 Node<K,V> n = findNode(k);
2175 if (n == null)
2176 return null;
2177 Object v = n.value;
2178 if (v != null && n.casValue(v, value))
2179 return (V)v;
2180 }
2181 }
2182
2183 /* ------ SortedMap API methods ------ */
2184
2185 public Comparator<? super K> comparator() {
2186 return comparator;
2187 }
2188
2189 /**
2190 * @throws NoSuchElementException {@inheritDoc}
2191 */
2192 public K firstKey() {
2193 Node<K,V> n = findFirst();
2194 if (n == null)
2195 throw new NoSuchElementException();
2196 return n.key;
2197 }
2198
2199 /**
2200 * @throws NoSuchElementException {@inheritDoc}
2201 */
2202 public K lastKey() {
2203 Node<K,V> n = findLast();
2204 if (n == null)
2205 throw new NoSuchElementException();
2206 return n.key;
2207 }
2208
2209 /**
2210 * @throws ClassCastException {@inheritDoc}
2211 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is null
2212 * @throws IllegalArgumentException {@inheritDoc}
2213 */
2214 public ConcurrentNavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
2215 if (fromKey == null || toKey == null)
2216 throw new NullPointerException();
2217 return new ConcurrentSkipListSubMap<K,V>(this, fromKey, toKey);
2218 }
2219
2220 /**
2221 * @throws ClassCastException {@inheritDoc}
2222 * @throws NullPointerException if <tt>toKey</tt> is null
2223 * @throws IllegalArgumentException {@inheritDoc}
2224 */
2225 public ConcurrentNavigableMap<K,V> navigableHeadMap(K toKey) {
2226 if (toKey == null)
2227 throw new NullPointerException();
2228 return new ConcurrentSkipListSubMap<K,V>(this, null, toKey);
2229 }
2230
2231 /**
2232 * @throws ClassCastException {@inheritDoc}
2233 * @throws NullPointerException if <tt>fromKey</tt> is null
2234 * @throws IllegalArgumentException {@inheritDoc}
2235 */
2236 public ConcurrentNavigableMap<K,V> navigableTailMap(K fromKey) {
2237 if (fromKey == null)
2238 throw new NullPointerException();
2239 return new ConcurrentSkipListSubMap<K,V>(this, fromKey, null);
2240 }
2241
2242 /**
2243 * Equivalent to {@link #navigableSubMap} but with a return type
2244 * conforming to the <tt>SortedMap</tt> interface.
2245 *
2246 * <p>{@inheritDoc}
2247 *
2248 * @throws ClassCastException {@inheritDoc}
2249 * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is null
2250 * @throws IllegalArgumentException {@inheritDoc}
2251 */
2252 public SortedMap<K,V> subMap(K fromKey, K toKey) {
2253 return navigableSubMap(fromKey, toKey);
2254 }
2255
2256 /**
2257 * Equivalent to {@link #navigableHeadMap} but with a return type
2258 * conforming to the <tt>SortedMap</tt> interface.
2259 *
2260 * <p>{@inheritDoc}
2261 *
2262 * @throws ClassCastException {@inheritDoc}
2263 * @throws NullPointerException if <tt>toKey</tt> is null
2264 * @throws IllegalArgumentException {@inheritDoc}
2265 */
2266 public SortedMap<K,V> headMap(K toKey) {
2267 return navigableHeadMap(toKey);
2268 }
2269
2270 /**
2271 * Equivalent to {@link #navigableTailMap} but with a return type
2272 * conforming to the <tt>SortedMap</tt> interface.
2273 *
2274 * <p>{@inheritDoc}
2275 *
2276 * @throws ClassCastException {@inheritDoc}
2277 * @throws NullPointerException if <tt>fromKey</tt> is null
2278 * @throws IllegalArgumentException {@inheritDoc}
2279 */
2280 public SortedMap<K,V> tailMap(K fromKey) {
2281 return navigableTailMap(fromKey);
2282 }
2283
2284 /* ---------------- Relational operations -------------- */
2285
2286 /**
2287 * Returns a key-value mapping associated with the greatest key
2288 * strictly less than the given key, or <tt>null</tt> if there is
2289 * no such key. The returned entry does <em>not</em> support the
2290 * <tt>Entry.setValue</tt> method.
2291 *
2292 * @throws ClassCastException {@inheritDoc}
2293 * @throws NullPointerException if the specified key is null
2294 */
2295 public Map.Entry<K,V> lowerEntry(K key) {
2296 return getNear(key, LT);
2297 }
2298
2299 /**
2300 * @throws ClassCastException {@inheritDoc}
2301 * @throws NullPointerException if the specified key is null
2302 */
2303 public K lowerKey(K key) {
2304 Node<K,V> n = findNear(key, LT);
2305 return (n == null)? null : n.key;
2306 }
2307
2308 /**
2309 * Returns a key-value mapping associated with the greatest key
2310 * less than or equal to the given key, or <tt>null</tt> if there
2311 * is no such key. The returned entry does <em>not</em> support
2312 * the <tt>Entry.setValue</tt> method.
2313 *
2314 * @param key the key
2315 * @throws ClassCastException {@inheritDoc}
2316 * @throws NullPointerException if the specified key is null
2317 */
2318 public Map.Entry<K,V> floorEntry(K key) {
2319 return getNear(key, LT|EQ);
2320 }
2321
2322 /**
2323 * @param key the key
2324 * @throws ClassCastException {@inheritDoc}
2325 * @throws NullPointerException if the specified key is null
2326 */
2327 public K floorKey(K key) {
2328 Node<K,V> n = findNear(key, LT|EQ);
2329 return (n == null)? null : n.key;
2330 }
2331
2332 /**
2333 * Returns a key-value mapping associated with the least key
2334 * greater than or equal to the given key, or <tt>null</tt> if
2335 * there is no such entry. The returned entry does <em>not</em>
2336 * support the <tt>Entry.setValue</tt> method.
2337 *
2338 * @throws ClassCastException {@inheritDoc}
2339 * @throws NullPointerException if the specified key is null
2340 */
2341 public Map.Entry<K,V> ceilingEntry(K key) {
2342 return getNear(key, GT|EQ);
2343 }
2344
2345 /**
2346 * @throws ClassCastException {@inheritDoc}
2347 * @throws NullPointerException if the specified key is null
2348 */
2349 public K ceilingKey(K key) {
2350 Node<K,V> n = findNear(key, GT|EQ);
2351 return (n == null)? null : n.key;
2352 }
2353
2354 /**
2355 * Returns a key-value mapping associated with the least key
2356 * strictly greater than the given key, or <tt>null</tt> if there
2357 * is no such key. The returned entry does <em>not</em> support
2358 * the <tt>Entry.setValue</tt> method.
2359 *
2360 * @param key the key
2361 * @throws ClassCastException {@inheritDoc}
2362 * @throws NullPointerException if the specified key is null
2363 */
2364 public Map.Entry<K,V> higherEntry(K key) {
2365 return getNear(key, GT);
2366 }
2367
2368 /**
2369 * @param key the key
2370 * @throws ClassCastException {@inheritDoc}
2371 * @throws NullPointerException if the specified key is null
2372 */
2373 public K higherKey(K key) {
2374 Node<K,V> n = findNear(key, GT);
2375 return (n == null)? null : n.key;
2376 }
2377
2378 /**
2379 * Returns a key-value mapping associated with the least
2380 * key in this map, or <tt>null</tt> if the map is empty.
2381 * The returned entry does <em>not</em> support
2382 * the <tt>Entry.setValue</tt> method.
2383 */
2384 public Map.Entry<K,V> firstEntry() {
2385 for (;;) {
2386 Node<K,V> n = findFirst();
2387 if (n == null)
2388 return null;
2389 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2390 if (e != null)
2391 return e;
2392 }
2393 }
2394
2395 /**
2396 * Returns a key-value mapping associated with the greatest
2397 * key in this map, or <tt>null</tt> if the map is empty.
2398 * The returned entry does <em>not</em> support
2399 * the <tt>Entry.setValue</tt> method.
2400 */
2401 public Map.Entry<K,V> lastEntry() {
2402 for (;;) {
2403 Node<K,V> n = findLast();
2404 if (n == null)
2405 return null;
2406 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2407 if (e != null)
2408 return e;
2409 }
2410 }
2411
2412 /**
2413 * Removes and returns a key-value mapping associated with
2414 * the least key in this map, or <tt>null</tt> if the map is empty.
2415 * The returned entry does <em>not</em> support
2416 * the <tt>Entry.setValue</tt> method.
2417 */
2418 public Map.Entry<K,V> pollFirstEntry() {
2419 return doRemoveFirstEntry();
2420 }
2421
2422 /**
2423 * Removes and returns a key-value mapping associated with
2424 * the greatest key in this map, or <tt>null</tt> if the map is empty.
2425 * The returned entry does <em>not</em> support
2426 * the <tt>Entry.setValue</tt> method.
2427 */
2428 public Map.Entry<K,V> pollLastEntry() {
2429 return doRemoveLastEntry();
2430 }
2431
2432
2433 /* ---------------- Iterators -------------- */
2434
2435 /**
2436 * Base of ten kinds of iterator classes:
2437 * ascending: {map, submap} X {key, value, entry}
2438 * descending: {map, submap} X {key, entry}
2439 */
2440 abstract class Iter {
2441 /** the last node returned by next() */
2442 Node<K,V> last;
2443 /** the next node to return from next(); */
2444 Node<K,V> next;
2445 /** Cache of next value field to maintain weak consistency */
2446 Object nextValue;
2447
2448 Iter() {}
2449
2450 public final boolean hasNext() {
2451 return next != null;
2452 }
2453
2454 /** Initializes ascending iterator for entire range. */
2455 final void initAscending() {
2456 for (;;) {
2457 next = findFirst();
2458 if (next == null)
2459 break;
2460 nextValue = next.value;
2461 if (nextValue != null && nextValue != next)
2462 break;
2463 }
2464 }
2465
2466 /**
2467 * Initializes ascending iterator starting at given least key,
2468 * or first node if least is <tt>null</tt>, but not greater or
2469 * equal to fence, or end if fence is <tt>null</tt>.
2470 */
2471 final void initAscending(K least, K fence) {
2472 for (;;) {
2473 next = findCeiling(least);
2474 if (next == null)
2475 break;
2476 nextValue = next.value;
2477 if (nextValue != null && nextValue != next) {
2478 if (fence != null && compare(fence, next.key) <= 0) {
2479 next = null;
2480 nextValue = null;
2481 }
2482 break;
2483 }
2484 }
2485 }
2486 /** Advances next to higher entry. */
2487 final void ascend() {
2488 if ((last = next) == null)
2489 throw new NoSuchElementException();
2490 for (;;) {
2491 next = next.next;
2492 if (next == null)
2493 break;
2494 nextValue = next.value;
2495 if (nextValue != null && nextValue != next)
2496 break;
2497 }
2498 }
2499
2500 /**
2501 * Version of ascend for submaps to stop at fence
2502 */
2503 final void ascend(K fence) {
2504 if ((last = next) == null)
2505 throw new NoSuchElementException();
2506 for (;;) {
2507 next = next.next;
2508 if (next == null)
2509 break;
2510 nextValue = next.value;
2511 if (nextValue != null && nextValue != next) {
2512 if (fence != null && compare(fence, next.key) <= 0) {
2513 next = null;
2514 nextValue = null;
2515 }
2516 break;
2517 }
2518 }
2519 }
2520
2521 /** Initializes descending iterator for entire range. */
2522 final void initDescending() {
2523 for (;;) {
2524 next = findLast();
2525 if (next == null)
2526 break;
2527 nextValue = next.value;
2528 if (nextValue != null && nextValue != next)
2529 break;
2530 }
2531 }
2532
2533 /**
2534 * Initializes descending iterator starting at key less
2535 * than or equal to given fence key, or
2536 * last node if fence is <tt>null</tt>, but not less than
2537 * least, or beginning if least is <tt>null</tt>.
2538 */
2539 final void initDescending(K least, K fence) {
2540 for (;;) {
2541 next = findLower(fence);
2542 if (next == null)
2543 break;
2544 nextValue = next.value;
2545 if (nextValue != null && nextValue != next) {
2546 if (least != null && compare(least, next.key) > 0) {
2547 next = null;
2548 nextValue = null;
2549 }
2550 break;
2551 }
2552 }
2553 }
2554
2555 /** Advances next to lower entry. */
2556 final void descend() {
2557 if ((last = next) == null)
2558 throw new NoSuchElementException();
2559 K k = last.key;
2560 for (;;) {
2561 next = findNear(k, LT);
2562 if (next == null)
2563 break;
2564 nextValue = next.value;
2565 if (nextValue != null && nextValue != next)
2566 break;
2567 }
2568 }
2569
2570 /**
2571 * Version of descend for submaps to stop at least
2572 */
2573 final void descend(K least) {
2574 if ((last = next) == null)
2575 throw new NoSuchElementException();
2576 K k = last.key;
2577 for (;;) {
2578 next = findNear(k, LT);
2579 if (next == null)
2580 break;
2581 nextValue = next.value;
2582 if (nextValue != null && nextValue != next) {
2583 if (least != null && compare(least, next.key) > 0) {
2584 next = null;
2585 nextValue = null;
2586 }
2587 break;
2588 }
2589 }
2590 }
2591
2592 public void remove() {
2593 Node<K,V> l = last;
2594 if (l == null)
2595 throw new IllegalStateException();
2596 // It would not be worth all of the overhead to directly
2597 // unlink from here. Using remove is fast enough.
2598 ConcurrentSkipListMap.this.remove(l.key);
2599 }
2600
2601 }
2602
2603 final class ValueIterator extends Iter implements Iterator<V> {
2604 ValueIterator() {
2605 initAscending();
2606 }
2607 public V next() {
2608 Object v = nextValue;
2609 ascend();
2610 return (V)v;
2611 }
2612 }
2613
2614 final class KeyIterator extends Iter implements Iterator<K> {
2615 KeyIterator() {
2616 initAscending();
2617 }
2618 public K next() {
2619 Node<K,V> n = next;
2620 ascend();
2621 return n.key;
2622 }
2623 }
2624
2625 class SubMapValueIterator extends Iter implements Iterator<V> {
2626 final K fence;
2627 SubMapValueIterator(K least, K fence) {
2628 initAscending(least, fence);
2629 this.fence = fence;
2630 }
2631
2632 public V next() {
2633 Object v = nextValue;
2634 ascend(fence);
2635 return (V)v;
2636 }
2637 }
2638
2639 final class SubMapKeyIterator extends Iter implements Iterator<K> {
2640 final K fence;
2641 SubMapKeyIterator(K least, K fence) {
2642 initAscending(least, fence);
2643 this.fence = fence;
2644 }
2645
2646 public K next() {
2647 Node<K,V> n = next;
2648 ascend(fence);
2649 return n.key;
2650 }
2651 }
2652
2653 final class DescendingKeyIterator extends Iter implements Iterator<K> {
2654 DescendingKeyIterator() {
2655 initDescending();
2656 }
2657 public K next() {
2658 Node<K,V> n = next;
2659 descend();
2660 return n.key;
2661 }
2662 }
2663
2664 final class DescendingSubMapKeyIterator extends Iter implements Iterator<K> {
2665 final K least;
2666 DescendingSubMapKeyIterator(K least, K fence) {
2667 initDescending(least, fence);
2668 this.least = least;
2669 }
2670
2671 public K next() {
2672 Node<K,V> n = next;
2673 descend(least);
2674 return n.key;
2675 }
2676 }
2677
2678 /**
2679 * Entry iterators use the same trick as in ConcurrentHashMap and
2680 * elsewhere of using the iterator itself to represent entries,
2681 * thus avoiding having to create entry objects in next().
2682 */
2683 abstract class EntryIter extends Iter implements Map.Entry<K,V> {
2684 /** Cache of last value returned */
2685 Object lastValue;
2686
2687 EntryIter() {
2688 }
2689
2690 public K getKey() {
2691 Node<K,V> l = last;
2692 if (l == null)
2693 throw new IllegalStateException();
2694 return l.key;
2695 }
2696
2697 public V getValue() {
2698 Object v = lastValue;
2699 if (last == null || v == null)
2700 throw new IllegalStateException();
2701 return (V)v;
2702 }
2703
2704 public V setValue(V value) {
2705 throw new UnsupportedOperationException();
2706 }
2707
2708 public boolean equals(Object o) {
2709 // If not acting as entry, just use default.
2710 if (last == null)
2711 return super.equals(o);
2712 if (!(o instanceof Map.Entry))
2713 return false;
2714 Map.Entry e = (Map.Entry)o;
2715 return (getKey().equals(e.getKey()) &&
2716 getValue().equals(e.getValue()));
2717 }
2718
2719 public int hashCode() {
2720 // If not acting as entry, just use default.
2721 if (last == null)
2722 return super.hashCode();
2723 return getKey().hashCode() ^ getValue().hashCode();
2724 }
2725
2726 public String toString() {
2727 // If not acting as entry, just use default.
2728 if (last == null)
2729 return super.toString();
2730 return getKey() + "=" + getValue();
2731 }
2732 }
2733
2734 final class EntryIterator extends EntryIter
2735 implements Iterator<Map.Entry<K,V>> {
2736 EntryIterator() {
2737 initAscending();
2738 }
2739 public Map.Entry<K,V> next() {
2740 lastValue = nextValue;
2741 ascend();
2742 return this;
2743 }
2744 }
2745
2746 final class SubMapEntryIterator extends EntryIter
2747 implements Iterator<Map.Entry<K,V>> {
2748 final K fence;
2749 SubMapEntryIterator(K least, K fence) {
2750 initAscending(least, fence);
2751 this.fence = fence;
2752 }
2753
2754 public Map.Entry<K,V> next() {
2755 lastValue = nextValue;
2756 ascend(fence);
2757 return this;
2758 }
2759 }
2760
2761 final class DescendingEntryIterator extends EntryIter
2762 implements Iterator<Map.Entry<K,V>> {
2763 DescendingEntryIterator() {
2764 initDescending();
2765 }
2766 public Map.Entry<K,V> next() {
2767 lastValue = nextValue;
2768 descend();
2769 return this;
2770 }
2771 }
2772
2773 final class DescendingSubMapEntryIterator extends EntryIter
2774 implements Iterator<Map.Entry<K,V>> {
2775 final K least;
2776 DescendingSubMapEntryIterator(K least, K fence) {
2777 initDescending(least, fence);
2778 this.least = least;
2779 }
2780
2781 public Map.Entry<K,V> next() {
2782 lastValue = nextValue;
2783 descend(least);
2784 return this;
2785 }
2786 }
2787
2788 // Factory methods for iterators needed by submaps and/or
2789 // ConcurrentSkipListSet
2790
2791 Iterator<K> keyIterator() {
2792 return new KeyIterator();
2793 }
2794
2795 Iterator<K> descendingKeyIterator() {
2796 return new DescendingKeyIterator();
2797 }
2798
2799 SubMapEntryIterator subMapEntryIterator(K least, K fence) {
2800 return new SubMapEntryIterator(least, fence);
2801 }
2802
2803 DescendingSubMapEntryIterator descendingSubMapEntryIterator(K least, K fence) {
2804 return new DescendingSubMapEntryIterator(least, fence);
2805 }
2806
2807 SubMapKeyIterator subMapKeyIterator(K least, K fence) {
2808 return new SubMapKeyIterator(least, fence);
2809 }
2810
2811 DescendingSubMapKeyIterator descendingSubMapKeyIterator(K least, K fence) {
2812 return new DescendingSubMapKeyIterator(least, fence);
2813 }
2814
2815 SubMapValueIterator subMapValueIterator(K least, K fence) {
2816 return new SubMapValueIterator(least, fence);
2817 }
2818
2819 /* ---------------- Views -------------- */
2820
2821 class KeySet extends AbstractSet<K> {
2822 public Iterator<K> iterator() {
2823 return new KeyIterator();
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.containsKey(o);
2833 }
2834 public boolean remove(Object o) {
2835 return ConcurrentSkipListMap.this.removep(o);
2836 }
2837 public void clear() {
2838 ConcurrentSkipListMap.this.clear();
2839 }
2840 public Object[] toArray() {
2841 Collection<K> c = new ArrayList<K>();
2842 for (Iterator<K> i = iterator(); i.hasNext(); )
2843 c.add(i.next());
2844 return c.toArray();
2845 }
2846 public <T> T[] toArray(T[] a) {
2847 Collection<K> c = new ArrayList<K>();
2848 for (Iterator<K> i = iterator(); i.hasNext(); )
2849 c.add(i.next());
2850 return c.toArray(a);
2851 }
2852 }
2853
2854 class DescendingKeySet extends KeySet {
2855 public Iterator<K> iterator() {
2856 return new DescendingKeyIterator();
2857 }
2858 }
2859
2860 final class Values extends AbstractCollection<V> {
2861 public Iterator<V> iterator() {
2862 return new ValueIterator();
2863 }
2864 public boolean isEmpty() {
2865 return ConcurrentSkipListMap.this.isEmpty();
2866 }
2867 public int size() {
2868 return ConcurrentSkipListMap.this.size();
2869 }
2870 public boolean contains(Object o) {
2871 return ConcurrentSkipListMap.this.containsValue(o);
2872 }
2873 public void clear() {
2874 ConcurrentSkipListMap.this.clear();
2875 }
2876 public Object[] toArray() {
2877 Collection<V> c = new ArrayList<V>();
2878 for (Iterator<V> i = iterator(); i.hasNext(); )
2879 c.add(i.next());
2880 return c.toArray();
2881 }
2882 public <T> T[] toArray(T[] a) {
2883 Collection<V> c = new ArrayList<V>();
2884 for (Iterator<V> i = iterator(); i.hasNext(); )
2885 c.add(i.next());
2886 return c.toArray(a);
2887 }
2888 }
2889
2890 class EntrySet extends AbstractSet<Map.Entry<K,V>> {
2891 public Iterator<Map.Entry<K,V>> iterator() {
2892 return new EntryIterator();
2893 }
2894 public boolean contains(Object o) {
2895 if (!(o instanceof Map.Entry))
2896 return false;
2897 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
2898 V v = ConcurrentSkipListMap.this.get(e.getKey());
2899 return v != null && v.equals(e.getValue());
2900 }
2901 public boolean remove(Object o) {
2902 if (!(o instanceof Map.Entry))
2903 return false;
2904 Map.Entry<K,V> e = (Map.Entry<K,V>)o;
2905 return ConcurrentSkipListMap.this.remove(e.getKey(),
2906 e.getValue());
2907 }
2908 public boolean isEmpty() {
2909 return ConcurrentSkipListMap.this.isEmpty();
2910 }
2911 public int size() {
2912 return ConcurrentSkipListMap.this.size();
2913 }
2914 public void clear() {
2915 ConcurrentSkipListMap.this.clear();
2916 }
2917 public Object[] toArray() {
2918 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
2919 for (Map.Entry<K,V> e : this)
2920 c.add(new AbstractMap.SimpleEntry<K,V>(e.getKey(),
2921 e.getValue()));
2922 return c.toArray();
2923 }
2924 public <T> T[] toArray(T[] a) {
2925 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
2926 for (Map.Entry<K,V> e : this)
2927 c.add(new AbstractMap.SimpleEntry<K,V>(e.getKey(),
2928 e.getValue()));
2929 return c.toArray(a);
2930 }
2931 }
2932
2933 class DescendingEntrySet extends EntrySet {
2934 public Iterator<Map.Entry<K,V>> iterator() {
2935 return new DescendingEntryIterator();
2936 }
2937 }
2938
2939 /**
2940 * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2941 * represent a subrange of mappings of their underlying
2942 * maps. Instances of this class support all methods of their
2943 * underlying maps, differing in that mappings outside their range are
2944 * ignored, and attempts to add mappings outside their ranges result
2945 * in {@link IllegalArgumentException}. Instances of this class are
2946 * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2947 * <tt>tailMap</tt> methods of their underlying maps.
2948 */
2949 static class ConcurrentSkipListSubMap<K,V> extends AbstractMap<K,V>
2950 implements ConcurrentNavigableMap<K,V>, java.io.Serializable {
2951
2952 private static final long serialVersionUID = -7647078645895051609L;
2953
2954 /** Underlying map */
2955 private final ConcurrentSkipListMap<K,V> m;
2956 /** lower bound key, or null if from start */
2957 private final K least;
2958 /** upper fence key, or null if to end */
2959 private final K fence;
2960 // Lazily initialized view holders
2961 private transient Set<K> keySetView;
2962 private transient Set<Map.Entry<K,V>> entrySetView;
2963 private transient Collection<V> valuesView;
2964 private transient Set<K> descendingKeySetView;
2965 private transient Set<Map.Entry<K,V>> descendingEntrySetView;
2966
2967 /**
2968 * Creates a new submap.
2969 * @param least inclusive least value, or <tt>null</tt> if from start
2970 * @param fence exclusive upper bound or <tt>null</tt> if to end
2971 * @throws IllegalArgumentException if least and fence nonnull
2972 * and least greater than fence
2973 */
2974 ConcurrentSkipListSubMap(ConcurrentSkipListMap<K,V> map,
2975 K least, K fence) {
2976 if (least != null &&
2977 fence != null &&
2978 map.compare(least, fence) > 0)
2979 throw new IllegalArgumentException("inconsistent range");
2980 this.m = map;
2981 this.least = least;
2982 this.fence = fence;
2983 }
2984
2985 /* ---------------- Utilities -------------- */
2986
2987 boolean inHalfOpenRange(K key) {
2988 return m.inHalfOpenRange(key, least, fence);
2989 }
2990
2991 boolean inOpenRange(K key) {
2992 return m.inOpenRange(key, least, fence);
2993 }
2994
2995 ConcurrentSkipListMap.Node<K,V> firstNode() {
2996 return m.findCeiling(least);
2997 }
2998
2999 ConcurrentSkipListMap.Node<K,V> lastNode() {
3000 return m.findLower(fence);
3001 }
3002
3003 boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
3004 return (n != null &&
3005 (fence == null ||
3006 n.key == null || // pass by markers and headers
3007 m.compare(fence, n.key) > 0));
3008 }
3009
3010 void checkKey(K key) throws IllegalArgumentException {
3011 if (!inHalfOpenRange(key))
3012 throw new IllegalArgumentException("key out of range");
3013 }
3014
3015 /**
3016 * Returns underlying map. Needed by ConcurrentSkipListSet
3017 * @return the backing map
3018 */
3019 ConcurrentSkipListMap<K,V> getMap() {
3020 return m;
3021 }
3022
3023 /**
3024 * Returns least key. Needed by ConcurrentSkipListSet
3025 * @return least key or <tt>null</tt> if from start
3026 */
3027 K getLeast() {
3028 return least;
3029 }
3030
3031 /**
3032 * Returns fence key. Needed by ConcurrentSkipListSet
3033 * @return fence key or <tt>null</tt> if to end
3034 */
3035 K getFence() {
3036 return fence;
3037 }
3038
3039
3040 /* ---------------- Map API methods -------------- */
3041
3042 public boolean containsKey(Object key) {
3043 K k = (K)key;
3044 return inHalfOpenRange(k) && m.containsKey(k);
3045 }
3046
3047 public V get(Object key) {
3048 K k = (K)key;
3049 return ((!inHalfOpenRange(k)) ? null : m.get(k));
3050 }
3051
3052 public V put(K key, V value) {
3053 checkKey(key);
3054 return m.put(key, value);
3055 }
3056
3057 public V remove(Object key) {
3058 K k = (K)key;
3059 return (!inHalfOpenRange(k))? null : m.remove(k);
3060 }
3061
3062 public int size() {
3063 long count = 0;
3064 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3065 isBeforeEnd(n);
3066 n = n.next) {
3067 if (n.getValidValue() != null)
3068 ++count;
3069 }
3070 return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count;
3071 }
3072
3073 public boolean isEmpty() {
3074 return !isBeforeEnd(firstNode());
3075 }
3076
3077 public boolean containsValue(Object value) {
3078 if (value == null)
3079 throw new NullPointerException();
3080 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3081 isBeforeEnd(n);
3082 n = n.next) {
3083 V v = n.getValidValue();
3084 if (v != null && value.equals(v))
3085 return true;
3086 }
3087 return false;
3088 }
3089
3090 public void clear() {
3091 for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3092 isBeforeEnd(n);
3093 n = n.next) {
3094 if (n.getValidValue() != null)
3095 m.remove(n.key);
3096 }
3097 }
3098
3099 /* ---------------- ConcurrentMap API methods -------------- */
3100
3101 public V putIfAbsent(K key, V value) {
3102 checkKey(key);
3103 return m.putIfAbsent(key, value);
3104 }
3105
3106 public boolean remove(Object key, Object value) {
3107 K k = (K)key;
3108 return inHalfOpenRange(k) && m.remove(k, value);
3109 }
3110
3111 public boolean replace(K key, V oldValue, V newValue) {
3112 checkKey(key);
3113 return m.replace(key, oldValue, newValue);
3114 }
3115
3116 public V replace(K key, V value) {
3117 checkKey(key);
3118 return m.replace(key, value);
3119 }
3120
3121 /* ---------------- SortedMap API methods -------------- */
3122
3123 public Comparator<? super K> comparator() {
3124 return m.comparator();
3125 }
3126
3127 public K firstKey() {
3128 ConcurrentSkipListMap.Node<K,V> n = firstNode();
3129 if (isBeforeEnd(n))
3130 return n.key;
3131 else
3132 throw new NoSuchElementException();
3133 }
3134
3135 public K lastKey() {
3136 ConcurrentSkipListMap.Node<K,V> n = lastNode();
3137 if (n != null) {
3138 K last = n.key;
3139 if (inHalfOpenRange(last))
3140 return last;
3141 }
3142 throw new NoSuchElementException();
3143 }
3144
3145 public ConcurrentNavigableMap<K,V> navigableSubMap(K fromKey, K toKey) {
3146 if (fromKey == null || toKey == null)
3147 throw new NullPointerException();
3148 if (!inOpenRange(fromKey) || !inOpenRange(toKey))
3149 throw new IllegalArgumentException("key out of range");
3150 return new ConcurrentSkipListSubMap<K,V>(m, fromKey, toKey);
3151 }
3152
3153 public ConcurrentNavigableMap<K,V> navigableHeadMap(K toKey) {
3154 if (toKey == null)
3155 throw new NullPointerException();
3156 if (!inOpenRange(toKey))
3157 throw new IllegalArgumentException("key out of range");
3158 return new ConcurrentSkipListSubMap<K,V>(m, least, toKey);
3159 }
3160
3161 public ConcurrentNavigableMap<K,V> navigableTailMap(K fromKey) {
3162 if (fromKey == null)
3163 throw new NullPointerException();
3164 if (!inOpenRange(fromKey))
3165 throw new IllegalArgumentException("key out of range");
3166 return new ConcurrentSkipListSubMap<K,V>(m, fromKey, fence);
3167 }
3168
3169 public SortedMap<K,V> subMap(K fromKey, K toKey) {
3170 return navigableSubMap(fromKey, toKey);
3171 }
3172
3173 public SortedMap<K,V> headMap(K toKey) {
3174 return navigableHeadMap(toKey);
3175 }
3176
3177 public SortedMap<K,V> tailMap(K fromKey) {
3178 return navigableTailMap(fromKey);
3179 }
3180
3181 /* ---------------- Relational methods -------------- */
3182
3183 public Map.Entry<K,V> ceilingEntry(K key) {
3184 return m.getNearEntry(key, m.GT|m.EQ, least, fence);
3185 }
3186
3187 public K ceilingKey(K key) {
3188 return m.getNearKey(key, m.GT|m.EQ, least, fence);
3189 }
3190
3191 public Map.Entry<K,V> lowerEntry(K key) {
3192 return m.getNearEntry(key, m.LT, least, fence);
3193 }
3194
3195 public K lowerKey(K key) {
3196 return m.getNearKey(key, m.LT, least, fence);
3197 }
3198
3199 public Map.Entry<K,V> floorEntry(K key) {
3200 return m.getNearEntry(key, m.LT|m.EQ, least, fence);
3201 }
3202
3203 public K floorKey(K key) {
3204 return m.getNearKey(key, m.LT|m.EQ, least, fence);
3205 }
3206
3207 public Map.Entry<K,V> higherEntry(K key) {
3208 return m.getNearEntry(key, m.GT, least, fence);
3209 }
3210
3211 public K higherKey(K key) {
3212 return m.getNearKey(key, m.GT, least, fence);
3213 }
3214
3215 public Map.Entry<K,V> firstEntry() {
3216 for (;;) {
3217 ConcurrentSkipListMap.Node<K,V> n = firstNode();
3218 if (!isBeforeEnd(n))
3219 return null;
3220 Map.Entry<K,V> e = n.createSnapshot();
3221 if (e != null)
3222 return e;
3223 }
3224 }
3225
3226 public Map.Entry<K,V> lastEntry() {
3227 for (;;) {
3228 ConcurrentSkipListMap.Node<K,V> n = lastNode();
3229 if (n == null || !inHalfOpenRange(n.key))
3230 return null;
3231 Map.Entry<K,V> e = n.createSnapshot();
3232 if (e != null)
3233 return e;
3234 }
3235 }
3236
3237 public Map.Entry<K,V> pollFirstEntry() {
3238 return m.removeFirstEntryOfSubrange(least, fence);
3239 }
3240
3241 public Map.Entry<K,V> pollLastEntry() {
3242 return m.removeLastEntryOfSubrange(least, fence);
3243 }
3244
3245 /* ---------------- Submap Views -------------- */
3246
3247 public Set<K> keySet() {
3248 Set<K> ks = keySetView;
3249 return (ks != null) ? ks : (keySetView = new KeySetView());
3250 }
3251
3252 class KeySetView extends AbstractSet<K> {
3253 public Iterator<K> iterator() {
3254 return m.subMapKeyIterator(least, fence);
3255 }
3256 public int size() {
3257 return ConcurrentSkipListSubMap.this.size();
3258 }
3259 public boolean isEmpty() {
3260 return ConcurrentSkipListSubMap.this.isEmpty();
3261 }
3262 public boolean contains(Object k) {
3263 return ConcurrentSkipListSubMap.this.containsKey(k);
3264 }
3265 public Object[] toArray() {
3266 Collection<K> c = new ArrayList<K>();
3267 for (Iterator<K> i = iterator(); i.hasNext(); )
3268 c.add(i.next());
3269 return c.toArray();
3270 }
3271 public <T> T[] toArray(T[] a) {
3272 Collection<K> c = new ArrayList<K>();
3273 for (Iterator<K> i = iterator(); i.hasNext(); )
3274 c.add(i.next());
3275 return c.toArray(a);
3276 }
3277 }
3278
3279 public Set<K> descendingKeySet() {
3280 Set<K> ks = descendingKeySetView;
3281 return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
3282 }
3283
3284 class DescendingKeySetView extends KeySetView {
3285 public Iterator<K> iterator() {
3286 return m.descendingSubMapKeyIterator(least, fence);
3287 }
3288 }
3289
3290 public Collection<V> values() {
3291 Collection<V> vs = valuesView;
3292 return (vs != null) ? vs : (valuesView = new ValuesView());
3293 }
3294
3295 class ValuesView extends AbstractCollection<V> {
3296 public Iterator<V> iterator() {
3297 return m.subMapValueIterator(least, fence);
3298 }
3299 public int size() {
3300 return ConcurrentSkipListSubMap.this.size();
3301 }
3302 public boolean isEmpty() {
3303 return ConcurrentSkipListSubMap.this.isEmpty();
3304 }
3305 public boolean contains(Object v) {
3306 return ConcurrentSkipListSubMap.this.containsValue(v);
3307 }
3308 public Object[] toArray() {
3309 Collection<V> c = new ArrayList<V>();
3310 for (Iterator<V> i = iterator(); i.hasNext(); )
3311 c.add(i.next());
3312 return c.toArray();
3313 }
3314 public <T> T[] toArray(T[] a) {
3315 Collection<V> c = new ArrayList<V>();
3316 for (Iterator<V> i = iterator(); i.hasNext(); )
3317 c.add(i.next());
3318 return c.toArray(a);
3319 }
3320 }
3321
3322 public Set<Map.Entry<K,V>> entrySet() {
3323 Set<Map.Entry<K,V>> es = entrySetView;
3324 return (es != null) ? es : (entrySetView = new EntrySetView());
3325 }
3326
3327 class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
3328 public Iterator<Map.Entry<K,V>> iterator() {
3329 return m.subMapEntryIterator(least, fence);
3330 }
3331 public int size() {
3332 return ConcurrentSkipListSubMap.this.size();
3333 }
3334 public boolean isEmpty() {
3335 return ConcurrentSkipListSubMap.this.isEmpty();
3336 }
3337 public boolean contains(Object o) {
3338 if (!(o instanceof Map.Entry))
3339 return false;
3340 Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3341 K key = e.getKey();
3342 if (!inHalfOpenRange(key))
3343 return false;
3344 V v = m.get(key);
3345 return v != null && v.equals(e.getValue());
3346 }
3347 public boolean remove(Object o) {
3348 if (!(o instanceof Map.Entry))
3349 return false;
3350 Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3351 K key = e.getKey();
3352 if (!inHalfOpenRange(key))
3353 return false;
3354 return m.remove(key, e.getValue());
3355 }
3356 public Object[] toArray() {
3357 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3358 for (Map.Entry<K,V> e : this)
3359 c.add(new AbstractMap.SimpleEntry<K,V>(e.getKey(),
3360 e.getValue()));
3361 return c.toArray();
3362 }
3363 public <T> T[] toArray(T[] a) {
3364 Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3365 for (Map.Entry<K,V> e : this)
3366 c.add(new AbstractMap.SimpleEntry<K,V>(e.getKey(),
3367 e.getValue()));
3368 return c.toArray(a);
3369 }
3370 }
3371
3372 public Set<Map.Entry<K,V>> descendingEntrySet() {
3373 Set<Map.Entry<K,V>> es = descendingEntrySetView;
3374 return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
3375 }
3376
3377 class DescendingEntrySetView extends EntrySetView {
3378 public Iterator<Map.Entry<K,V>> iterator() {
3379 return m.descendingSubMapEntryIterator(least, fence);
3380 }
3381 }
3382 }
3383 }