ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166x/ConcurrentSkipListMap.java
Revision: 1.4
Committed: Sat Oct 16 14:49:45 2004 UTC (19 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.3: +218 -175 lines
Log Message:
Improve pollLast* implementation; other minor touchups

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