ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.29
Committed: Sat May 28 15:09:37 2005 UTC (19 years ago) by jsr166
Branch: MAIN
Changes since 1.28: +1 -1 lines
Log Message:
whitespace

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