ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166x/ConcurrentSkipListMap.java
Revision: 1.1
Committed: Wed Aug 11 10:58:15 2004 UTC (19 years, 9 months ago) by dl
Branch: MAIN
Log Message:
Initial checkin of initial jsr166x package and skip list classes

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