ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.5
Committed: Tue Mar 8 12:27:11 2005 UTC (19 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.4: +4 -4 lines
Log Message:
Copyedit pass

File Contents

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