ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.21
Committed: Tue May 3 02:52:07 2005 UTC (19 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.20: +4 -0 lines
Log Message:
Update collections framework pointer

File Contents

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