ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.43
Committed: Sun Nov 20 15:38:08 2005 UTC (18 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.42: +29 -148 lines
Log Message:
Eliminate unnecessary special handling of toArray

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