ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.2
Committed: Fri Dec 31 13:00:39 2004 UTC (19 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.1: +54 -35 lines
Log Message:
Add AbstractMap.SimpleImmutableEntry; make SimpleEntry public

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     * (http://www.cl.cam.ac.uk/users/kaf24/), and Håkan Sundell's
268     * 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     /* ---------------- Map.Entry support -------------- */
577    
578     /**
579     * An immutable representation of a key-value mapping as it
580     * existed at some point in time. This class does <em>not</em>
581     * support the <tt>Map.Entry.setValue</tt> method.
582     */
583     static class SnapshotEntry<K,V> implements Map.Entry<K,V> {
584     private final K key;
585     private final V value;
586    
587     /**
588     * Creates a new entry representing the given key and value.
589     * @param key the key
590     * @param value the value
591     */
592     SnapshotEntry(K key, V value) {
593     this.key = key;
594     this.value = value;
595     }
596    
597     /**
598     * Returns the key corresponding to this entry.
599     *
600     * @return the key corresponding to this entry.
601     */
602     public K getKey() {
603     return key;
604     }
605    
606     /**
607     * Returns the value corresponding to this entry.
608     *
609     * @return the value corresponding to this entry.
610     */
611     public V getValue() {
612     return value;
613     }
614    
615     /**
616     * Always fails, throwing <tt>UnsupportedOperationException</tt>.
617     * @throws UnsupportedOperationException always.
618     */
619     public V setValue(V value) {
620     throw new UnsupportedOperationException();
621     }
622    
623     // inherit javadoc
624     public boolean equals(Object o) {
625     if (!(o instanceof Map.Entry))
626     return false;
627     Map.Entry e = (Map.Entry)o;
628     // As mandated by Map.Entry spec:
629     return ((key==null ?
630     e.getKey()==null : key.equals(e.getKey())) &&
631     (value==null ?
632     e.getValue()==null : value.equals(e.getValue())));
633     }
634    
635    
636     // inherit javadoc
637     public int hashCode() {
638     // As mandated by Map.Entry spec:
639     return ((key==null ? 0 : key.hashCode()) ^
640     (value==null ? 0 : value.hashCode()));
641     }
642    
643     /**
644     * Returns a String consisting of the key followed by an
645     * equals sign (<tt>"="</tt>) followed by the associated
646     * value.
647     * @return a String representation of this entry.
648     */
649     public String toString() {
650     return getKey() + "=" + getValue();
651     }
652     }
653    
654     /* ---------------- Comparison utilities -------------- */
655    
656     /**
657     * Represents a key with a comparator as a Comparable.
658     *
659     * Because most sorted collections seem to use natural order on
660     * Comparables (Strings, Integers, etc), most internal methods are
661     * geared to use them. This is generally faster than checking
662     * per-comparison whether to use comparator or comparable because
663     * it doesn't require a (Comparable) cast for each comparison.
664     * (Optimizers can only sometimes remove such redundant checks
665     * themselves.) When Comparators are used,
666     * ComparableUsingComparators are created so that they act in the
667     * same way as natural orderings. This penalizes use of
668     * Comparators vs Comparables, which seems like the right
669     * tradeoff.
670     */
671     static final class ComparableUsingComparator<K> implements Comparable<K> {
672     final K actualKey;
673     final Comparator<? super K> cmp;
674     ComparableUsingComparator(K key, Comparator<? super K> cmp) {
675     this.actualKey = key;
676     this.cmp = cmp;
677     }
678     public int compareTo(K k2) {
679     return cmp.compare(actualKey, k2);
680     }
681     }
682    
683     /**
684     * If using comparator, return a ComparableUsingComparator, else
685     * cast key as Comparator, which may cause ClassCastException,
686     * which is propagated back to caller.
687     */
688     private Comparable<K> comparable(Object key) throws ClassCastException {
689     if (key == null)
690     throw new NullPointerException();
691     return (comparator != null)
692     ? new ComparableUsingComparator(key, comparator)
693     : (Comparable<K>)key;
694     }
695    
696     /**
697     * Compare using comparator or natural ordering. Used when the
698     * ComparableUsingComparator approach doesn't apply.
699     */
700     int compare(K k1, K k2) throws ClassCastException {
701     Comparator<? super K> cmp = comparator;
702     if (cmp != null)
703     return cmp.compare(k1, k2);
704     else
705     return ((Comparable<K>)k1).compareTo(k2);
706     }
707    
708     /**
709     * Return true if given key greater than or equal to least and
710     * strictly less than fence, bypassing either test if least or
711     * fence oare null. Needed mainly in submap operations.
712     */
713     boolean inHalfOpenRange(K key, K least, K fence) {
714     if (key == null)
715     throw new NullPointerException();
716     return ((least == null || compare(key, least) >= 0) &&
717     (fence == null || compare(key, fence) < 0));
718     }
719    
720     /**
721     * Return true if given key greater than or equal to least and less
722     * or equal to fence. Needed mainly in submap operations.
723     */
724     boolean inOpenRange(K key, K least, K fence) {
725     if (key == null)
726     throw new NullPointerException();
727     return ((least == null || compare(key, least) >= 0) &&
728     (fence == null || compare(key, fence) <= 0));
729     }
730    
731     /* ---------------- Traversal -------------- */
732    
733     /**
734     * Return a base-level node with key strictly less than given key,
735     * or the base-level header if there is no such node. Also
736     * unlinks indexes to deleted nodes found along the way. Callers
737     * rely on this side-effect of clearing indices to deleted nodes.
738     * @param key the key
739     * @return a predecessor of key
740     */
741     private Node<K,V> findPredecessor(Comparable<K> key) {
742     for (;;) {
743     Index<K,V> q = head;
744     for (;;) {
745     Index<K,V> d, r;
746     if ((r = q.right) != null) {
747     if (r.indexesDeletedNode()) {
748     if (q.unlink(r))
749     continue; // reread r
750     else
751     break; // restart
752     }
753     if (key.compareTo(r.key) > 0) {
754     q = r;
755     continue;
756     }
757     }
758     if ((d = q.down) != null)
759     q = d;
760     else
761     return q.node;
762     }
763     }
764     }
765    
766     /**
767     * Return node holding key or null if no such, clearing out any
768     * deleted nodes seen along the way. Repeatedly traverses at
769     * base-level looking for key starting at predecessor returned
770     * from findPredecessor, processing base-level deletions as
771     * encountered. Some callers rely on this side-effect of clearing
772     * deleted nodes.
773     *
774     * Restarts occur, at traversal step centered on node n, if:
775     *
776     * (1) After reading n's next field, n is no longer assumed
777     * predecessor b's current successor, which means that
778     * we don't have a consistent 3-node snapshot and so cannot
779     * unlink any subsequent deleted nodes encountered.
780     *
781     * (2) n's value field is null, indicating n is deleted, in
782     * which case we help out an ongoing structural deletion
783     * before retrying. Even though there are cases where such
784     * unlinking doesn't require restart, they aren't sorted out
785     * here because doing so would not usually outweigh cost of
786     * restarting.
787     *
788     * (3) n is a marker or n's predecessor's value field is null,
789     * indicating (among other possibilities) that
790     * findPredecessor returned a deleted node. We can't unlink
791     * the node because we don't know its predecessor, so rely
792     * on another call to findPredecessor to notice and return
793     * some earlier predecessor, which it will do. This check is
794     * only strictly needed at beginning of loop, (and the
795     * b.value check isn't strictly needed at all) but is done
796     * each iteration to help avoid contention with other
797     * threads by callers that will fail to be able to change
798     * links, and so will retry anyway.
799     *
800     * The traversal loops in doPut, doRemove, and findNear all
801     * include the same three kinds of checks. And specialized
802     * versions appear in doRemoveFirst, doRemoveLast, findFirst, and
803     * findLast. They can't easily share code because each uses the
804     * reads of fields held in locals occurring in the orders they
805     * were performed.
806     *
807     * @param key the key
808     * @return node holding key, or null if no such.
809     */
810     private Node<K,V> findNode(Comparable<K> key) {
811     for (;;) {
812     Node<K,V> b = findPredecessor(key);
813     Node<K,V> n = b.next;
814     for (;;) {
815     if (n == null)
816     return null;
817     Node<K,V> f = n.next;
818     if (n != b.next) // inconsistent read
819     break;
820     Object v = n.value;
821     if (v == null) { // n is deleted
822     n.helpDelete(b, f);
823     break;
824     }
825     if (v == n || b.value == null) // b is deleted
826     break;
827     int c = key.compareTo(n.key);
828     if (c < 0)
829     return null;
830     if (c == 0)
831     return n;
832     b = n;
833     n = f;
834     }
835     }
836     }
837    
838     /**
839     * Specialized variant of findNode to perform Map.get. Does a weak
840     * traversal, not bothering to fix any deleted index nodes,
841     * returning early if it happens to see key in index, and passing
842     * over any deleted base nodes, falling back to getUsingFindNode
843     * only if it would otherwise return value from an ongoing
844     * deletion. Also uses "bound" to eliminate need for some
845     * comparisons (see Pugh Cookbook). Also folds uses of null checks
846     * and node-skipping because markers have null keys.
847     * @param okey the key
848     * @return the value, or null if absent
849     */
850     private V doGet(Object okey) {
851     Comparable<K> key = comparable(okey);
852     K bound = null;
853     Index<K,V> q = head;
854     for (;;) {
855     K rk;
856     Index<K,V> d, r;
857     if ((r = q.right) != null &&
858     (rk = r.key) != null && rk != bound) {
859     int c = key.compareTo(rk);
860     if (c > 0) {
861     q = r;
862     continue;
863     }
864     if (c == 0) {
865     Object v = r.node.value;
866     return (v != null)? (V)v : getUsingFindNode(key);
867     }
868     bound = rk;
869     }
870     if ((d = q.down) != null)
871     q = d;
872     else {
873     for (Node<K,V> n = q.node.next; n != null; n = n.next) {
874     K nk = n.key;
875     if (nk != null) {
876     int c = key.compareTo(nk);
877     if (c == 0) {
878     Object v = n.value;
879     return (v != null)? (V)v : getUsingFindNode(key);
880     }
881     if (c < 0)
882     return null;
883     }
884     }
885     return null;
886     }
887     }
888     }
889    
890     /**
891     * Perform map.get via findNode. Used as a backup if doGet
892     * encounters an in-progress deletion.
893     * @param key the key
894     * @return the value, or null if absent
895     */
896     private V getUsingFindNode(Comparable<K> key) {
897     /*
898     * Loop needed here and elsewhere in case value field goes
899     * null just as it is about to be returned, in which case we
900     * lost a race with a deletion, so must retry.
901     */
902     for (;;) {
903     Node<K,V> n = findNode(key);
904     if (n == null)
905     return null;
906     Object v = n.value;
907     if (v != null)
908     return (V)v;
909     }
910     }
911    
912     /* ---------------- Insertion -------------- */
913    
914     /**
915     * Main insertion method. Adds element if not present, or
916     * replaces value if present and onlyIfAbsent is false.
917     * @param kkey the key
918     * @param value the value that must be associated with key
919     * @param onlyIfAbsent if should not insert if already present
920     * @return the old value, or null if newly inserted
921     */
922     private V doPut(K kkey, V value, boolean onlyIfAbsent) {
923     Comparable<K> key = comparable(kkey);
924     for (;;) {
925     Node<K,V> b = findPredecessor(key);
926     Node<K,V> n = b.next;
927     for (;;) {
928     if (n != null) {
929     Node<K,V> f = n.next;
930     if (n != b.next) // inconsistent read
931     break;;
932     Object v = n.value;
933     if (v == null) { // n is deleted
934     n.helpDelete(b, f);
935     break;
936     }
937     if (v == n || b.value == null) // b is deleted
938     break;
939     int c = key.compareTo(n.key);
940     if (c > 0) {
941     b = n;
942     n = f;
943     continue;
944     }
945     if (c == 0) {
946     if (onlyIfAbsent || n.casValue(v, value))
947     return (V)v;
948     else
949     break; // restart if lost race to replace value
950     }
951     // else c < 0; fall through
952     }
953    
954     Node<K,V> z = new Node<K,V>(kkey, value, n);
955     if (!b.casNext(n, z))
956     break; // restart if lost race to append to b
957     int level = randomLevel();
958     if (level > 0)
959     insertIndex(z, level);
960     return null;
961     }
962     }
963     }
964    
965     /**
966     * Return a random level for inserting a new node.
967     * Hardwired to k=1, p=0.5, max 31.
968     *
969     * This uses a cheap pseudo-random function that according to
970     * http://home1.gte.net/deleyd/random/random4.html was used in
971     * Turbo Pascal. It seems the fastest usable one here. The low
972     * bits are apparently not very random (the original used only
973     * upper 16 bits) so we traverse from highest bit down (i.e., test
974     * sign), thus hardly ever use lower bits.
975     */
976     private int randomLevel() {
977     int level = 0;
978     int r = randomSeed;
979     randomSeed = r * 134775813 + 1;
980     if (r < 0) {
981     while ((r <<= 1) > 0)
982     ++level;
983     }
984     return level;
985     }
986    
987     /**
988     * Create and add index nodes for given node.
989     * @param z the node
990     * @param level the level of the index
991     */
992     private void insertIndex(Node<K,V> z, int level) {
993     HeadIndex<K,V> h = head;
994     int max = h.level;
995    
996     if (level <= max) {
997     Index<K,V> idx = null;
998     for (int i = 1; i <= level; ++i)
999     idx = new Index<K,V>(z, idx, null);
1000     addIndex(idx, h, level);
1001    
1002     } else { // Add a new level
1003     /*
1004     * To reduce interference by other threads checking for
1005     * empty levels in tryReduceLevel, new levels are added
1006     * with initialized right pointers. Which in turn requires
1007     * keeping levels in an array to access them while
1008     * creating new head index nodes from the opposite
1009     * direction.
1010     */
1011     level = max + 1;
1012     Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
1013     Index<K,V> idx = null;
1014     for (int i = 1; i <= level; ++i)
1015     idxs[i] = idx = new Index<K,V>(z, idx, null);
1016    
1017     HeadIndex<K,V> oldh;
1018     int k;
1019     for (;;) {
1020     oldh = head;
1021     int oldLevel = oldh.level;
1022     if (level <= oldLevel) { // lost race to add level
1023     k = level;
1024     break;
1025     }
1026     HeadIndex<K,V> newh = oldh;
1027     Node<K,V> oldbase = oldh.node;
1028     for (int j = oldLevel+1; j <= level; ++j)
1029     newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
1030     if (casHead(oldh, newh)) {
1031     k = oldLevel;
1032     break;
1033     }
1034     }
1035     addIndex(idxs[k], oldh, k);
1036     }
1037     }
1038    
1039     /**
1040     * Add given index nodes from given level down to 1.
1041     * @param idx the topmost index node being inserted
1042     * @param h the value of head to use to insert. This must be
1043     * snapshotted by callers to provide correct insertion level
1044     * @param indexLevel the level of the index
1045     */
1046     private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
1047     // Track next level to insert in case of retries
1048     int insertionLevel = indexLevel;
1049     Comparable<K> key = comparable(idx.key);
1050    
1051     // Similar to findPredecessor, but adding index nodes along
1052     // path to key.
1053     for (;;) {
1054     Index<K,V> q = h;
1055     Index<K,V> t = idx;
1056     int j = h.level;
1057     for (;;) {
1058     Index<K,V> r = q.right;
1059     if (r != null) {
1060     // compare before deletion check avoids needing recheck
1061     int c = key.compareTo(r.key);
1062     if (r.indexesDeletedNode()) {
1063     if (q.unlink(r))
1064     continue;
1065     else
1066     break;
1067     }
1068     if (c > 0) {
1069     q = r;
1070     continue;
1071     }
1072     }
1073    
1074     if (j == insertionLevel) {
1075     // Don't insert index if node already deleted
1076     if (t.indexesDeletedNode()) {
1077     findNode(key); // cleans up
1078     return;
1079     }
1080     if (!q.link(r, t))
1081     break; // restart
1082     if (--insertionLevel == 0) {
1083     // need final deletion check before return
1084     if (t.indexesDeletedNode())
1085     findNode(key);
1086     return;
1087     }
1088     }
1089    
1090     if (j > insertionLevel && j <= indexLevel)
1091     t = t.down;
1092     q = q.down;
1093     --j;
1094     }
1095     }
1096     }
1097    
1098     /* ---------------- Deletion -------------- */
1099    
1100     /**
1101     * Main deletion method. Locates node, nulls value, appends a
1102     * deletion marker, unlinks predecessor, removes associated index
1103     * nodes, and possibly reduces head index level.
1104     *
1105     * Index nodes are cleared out simply by calling findPredecessor.
1106     * which unlinks indexes to deleted nodes found along path to key,
1107     * which will include the indexes to this node. This is done
1108     * unconditionally. We can't check beforehand whether there are
1109     * index nodes because it might be the case that some or all
1110     * indexes hadn't been inserted yet for this node during initial
1111     * search for it, and we'd like to ensure lack of garbage
1112     * retention, so must call to be sure.
1113     *
1114     * @param okey the key
1115     * @param value if non-null, the value that must be
1116     * associated with key
1117     * @return the node, or null if not found
1118     */
1119     private V doRemove(Object okey, Object value) {
1120     Comparable<K> key = comparable(okey);
1121     for (;;) {
1122     Node<K,V> b = findPredecessor(key);
1123     Node<K,V> n = b.next;
1124     for (;;) {
1125     if (n == null)
1126     return null;
1127     Node<K,V> f = n.next;
1128     if (n != b.next) // inconsistent read
1129     break;
1130     Object v = n.value;
1131     if (v == null) { // n is deleted
1132     n.helpDelete(b, f);
1133     break;
1134     }
1135     if (v == n || b.value == null) // b is deleted
1136     break;
1137     int c = key.compareTo(n.key);
1138     if (c < 0)
1139     return null;
1140     if (c > 0) {
1141     b = n;
1142     n = f;
1143     continue;
1144     }
1145     if (value != null && !value.equals(v))
1146     return null;
1147     if (!n.casValue(v, null))
1148     break;
1149     if (!n.appendMarker(f) || !b.casNext(n, f))
1150     findNode(key); // Retry via findNode
1151     else {
1152     findPredecessor(key); // Clean index
1153     if (head.right == null)
1154     tryReduceLevel();
1155     }
1156     return (V)v;
1157     }
1158     }
1159     }
1160    
1161     /**
1162     * Possibly reduce head level if it has no nodes. This method can
1163     * (rarely) make mistakes, in which case levels can disappear even
1164     * though they are about to contain index nodes. This impacts
1165     * performance, not correctness. To minimize mistakes as well as
1166     * to reduce hysteresis, the level is reduced by one only if the
1167     * topmost three levels look empty. Also, if the removed level
1168     * looks non-empty after CAS, we try to change it back quick
1169     * before anyone notices our mistake! (This trick works pretty
1170     * well because this method will practically never make mistakes
1171     * unless current thread stalls immediately before first CAS, in
1172     * which case it is very unlikely to stall again immediately
1173     * afterwards, so will recover.)
1174     *
1175     * We put up with all this rather than just let levels grow
1176     * because otherwise, even a small map that has undergone a large
1177     * number of insertions and removals will have a lot of levels,
1178     * slowing down access more than would an occasional unwanted
1179     * reduction.
1180     */
1181     private void tryReduceLevel() {
1182     HeadIndex<K,V> h = head;
1183     HeadIndex<K,V> d;
1184     HeadIndex<K,V> e;
1185     if (h.level > 3 &&
1186     (d = (HeadIndex<K,V>)h.down) != null &&
1187     (e = (HeadIndex<K,V>)d.down) != null &&
1188     e.right == null &&
1189     d.right == null &&
1190     h.right == null &&
1191     casHead(h, d) && // try to set
1192     h.right != null) // recheck
1193     casHead(d, h); // try to backout
1194     }
1195    
1196     /**
1197     * Version of remove with boolean return. Needed by view classes
1198     */
1199     boolean removep(Object key) {
1200     return doRemove(key, null) != null;
1201     }
1202    
1203     /* ---------------- Finding and removing first element -------------- */
1204    
1205     /**
1206     * Specialized variant of findNode to get first valid node
1207     * @return first node or null if empty
1208     */
1209     Node<K,V> findFirst() {
1210     for (;;) {
1211     Node<K,V> b = head.node;
1212     Node<K,V> n = b.next;
1213     if (n == null)
1214     return null;
1215     if (n.value != null)
1216     return n;
1217     n.helpDelete(b, n.next);
1218     }
1219     }
1220    
1221     /**
1222     * Remove first entry; return either its key or a snapshot.
1223 dl 1.2 * @param keyOnly if true return key, else return SimpleImmutableEntry
1224 dl 1.1 * (This is a little ugly, but avoids code duplication.)
1225     * @return null if empty, first key if keyOnly true, else key,value entry
1226     */
1227     Object doRemoveFirst(boolean keyOnly) {
1228     for (;;) {
1229     Node<K,V> b = head.node;
1230     Node<K,V> n = b.next;
1231     if (n == null)
1232     return null;
1233     Node<K,V> f = n.next;
1234     if (n != b.next)
1235     continue;
1236     Object v = n.value;
1237     if (v == null) {
1238     n.helpDelete(b, f);
1239     continue;
1240     }
1241     if (!n.casValue(v, null))
1242     continue;
1243     if (!n.appendMarker(f) || !b.casNext(n, f))
1244     findFirst(); // retry
1245     clearIndexToFirst();
1246     K key = n.key;
1247 dl 1.2 if (keyOnly)
1248     return key;
1249     else
1250     return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1251 dl 1.1 }
1252     }
1253    
1254     /**
1255     * Clear out index nodes associated with deleted first entry.
1256     * Needed by doRemoveFirst
1257     */
1258     private void clearIndexToFirst() {
1259     for (;;) {
1260     Index<K,V> q = head;
1261     for (;;) {
1262     Index<K,V> r = q.right;
1263     if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1264     break;
1265     if ((q = q.down) == null) {
1266     if (head.right == null)
1267     tryReduceLevel();
1268     return;
1269     }
1270     }
1271     }
1272     }
1273    
1274     /**
1275     * Remove first entry; return key or null if empty.
1276     */
1277     K pollFirstKey() {
1278     return (K)doRemoveFirst(true);
1279     }
1280    
1281     /* ---------------- Finding and removing last element -------------- */
1282    
1283     /**
1284     * Specialized version of find to get last valid node
1285     * @return last node or null if empty
1286     */
1287     Node<K,V> findLast() {
1288     /*
1289     * findPredecessor can't be used to traverse index level
1290     * because this doesn't use comparisons. So traversals of
1291     * both levels are folded together.
1292     */
1293     Index<K,V> q = head;
1294     for (;;) {
1295     Index<K,V> d, r;
1296     if ((r = q.right) != null) {
1297     if (r.indexesDeletedNode()) {
1298     q.unlink(r);
1299     q = head; // restart
1300     }
1301     else
1302     q = r;
1303     } else if ((d = q.down) != null) {
1304     q = d;
1305     } else {
1306     Node<K,V> b = q.node;
1307     Node<K,V> n = b.next;
1308     for (;;) {
1309     if (n == null)
1310     return (b.isBaseHeader())? null : b;
1311     Node<K,V> f = n.next; // inconsistent read
1312     if (n != b.next)
1313     break;
1314     Object v = n.value;
1315     if (v == null) { // n is deleted
1316     n.helpDelete(b, f);
1317     break;
1318     }
1319     if (v == n || b.value == null) // b is deleted
1320     break;
1321     b = n;
1322     n = f;
1323     }
1324     q = head; // restart
1325     }
1326     }
1327     }
1328    
1329    
1330     /**
1331     * Specialized version of doRemove for last entry.
1332 dl 1.2 * @param keyOnly if true return key, else return SimpleImmutableEntry
1333 dl 1.1 * @return null if empty, last key if keyOnly true, else key,value entry
1334     */
1335     Object doRemoveLast(boolean keyOnly) {
1336     for (;;) {
1337     Node<K,V> b = findPredecessorOfLast();
1338     Node<K,V> n = b.next;
1339     if (n == null) {
1340     if (b.isBaseHeader()) // empty
1341     return null;
1342     else
1343     continue; // all b's successors are deleted; retry
1344     }
1345     for (;;) {
1346     Node<K,V> f = n.next;
1347     if (n != b.next) // inconsistent read
1348     break;
1349     Object v = n.value;
1350     if (v == null) { // n is deleted
1351     n.helpDelete(b, f);
1352     break;
1353     }
1354     if (v == n || b.value == null) // b is deleted
1355     break;
1356     if (f != null) {
1357     b = n;
1358     n = f;
1359     continue;
1360     }
1361     if (!n.casValue(v, null))
1362     break;
1363     K key = n.key;
1364     Comparable<K> ck = comparable(key);
1365     if (!n.appendMarker(f) || !b.casNext(n, f))
1366     findNode(ck); // Retry via findNode
1367     else {
1368     findPredecessor(ck); // Clean index
1369     if (head.right == null)
1370     tryReduceLevel();
1371     }
1372 dl 1.2 if (keyOnly)
1373     return key;
1374     else
1375     return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1376 dl 1.1 }
1377     }
1378     }
1379    
1380     /**
1381     * Specialized variant of findPredecessor to get predecessor of
1382     * last valid node. Needed by doRemoveLast. It is possible that
1383     * all successors of returned node will have been deleted upon
1384     * return, in which case this method can be retried.
1385     * @return likely predecessor of last node.
1386     */
1387     private Node<K,V> findPredecessorOfLast() {
1388     for (;;) {
1389     Index<K,V> q = head;
1390     for (;;) {
1391     Index<K,V> d, r;
1392     if ((r = q.right) != null) {
1393     if (r.indexesDeletedNode()) {
1394     q.unlink(r);
1395     break; // must restart
1396     }
1397     // proceed as far across as possible without overshooting
1398     if (r.node.next != null) {
1399     q = r;
1400     continue;
1401     }
1402     }
1403     if ((d = q.down) != null)
1404     q = d;
1405     else
1406     return q.node;
1407     }
1408     }
1409     }
1410    
1411     /**
1412     * Remove last entry; return key or null if empty.
1413     */
1414     K pollLastKey() {
1415     return (K)doRemoveLast(true);
1416     }
1417    
1418     /* ---------------- Relational operations -------------- */
1419    
1420     // Control values OR'ed as arguments to findNear
1421    
1422     private static final int EQ = 1;
1423     private static final int LT = 2;
1424     private static final int GT = 0; // Actually checked as !LT
1425    
1426     /**
1427     * Utility for ceiling, floor, lower, higher methods.
1428     * @param kkey the key
1429     * @param rel the relation -- OR'ed combination of EQ, LT, GT
1430     * @return nearest node fitting relation, or null if no such
1431     */
1432     Node<K,V> findNear(K kkey, int rel) {
1433     Comparable<K> key = comparable(kkey);
1434     for (;;) {
1435     Node<K,V> b = findPredecessor(key);
1436     Node<K,V> n = b.next;
1437     for (;;) {
1438     if (n == null)
1439     return ((rel & LT) == 0 || b.isBaseHeader())? null : b;
1440     Node<K,V> f = n.next;
1441     if (n != b.next) // inconsistent read
1442     break;
1443     Object v = n.value;
1444     if (v == null) { // n is deleted
1445     n.helpDelete(b, f);
1446     break;
1447     }
1448     if (v == n || b.value == null) // b is deleted
1449     break;
1450     int c = key.compareTo(n.key);
1451     if ((c == 0 && (rel & EQ) != 0) ||
1452     (c < 0 && (rel & LT) == 0))
1453     return n;
1454     if ( c <= 0 && (rel & LT) != 0)
1455     return (b.isBaseHeader())? null : b;
1456     b = n;
1457     n = f;
1458     }
1459     }
1460     }
1461    
1462     /**
1463 dl 1.2 * Return SimpleImmutableEntry for results of findNear.
1464 dl 1.1 * @param kkey the key
1465     * @param rel the relation -- OR'ed combination of EQ, LT, GT
1466     * @return Entry fitting relation, or null if no such
1467     */
1468 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> getNear(K kkey, int rel) {
1469 dl 1.1 for (;;) {
1470     Node<K,V> n = findNear(kkey, rel);
1471     if (n == null)
1472     return null;
1473 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1474 dl 1.1 if (e != null)
1475     return e;
1476     }
1477     }
1478    
1479     /**
1480     * Return ceiling, or first node if key is <tt>null</tt>
1481     */
1482     Node<K,V> findCeiling(K key) {
1483     return (key == null)? findFirst() : findNear(key, GT|EQ);
1484     }
1485    
1486     /**
1487     * Return lower node, or last node if key is <tt>null</tt>
1488     */
1489     Node<K,V> findLower(K key) {
1490     return (key == null)? findLast() : findNear(key, LT);
1491     }
1492    
1493     /**
1494 dl 1.2 * Return SimpleImmutableEntry or key for results of findNear
1495     * ofter screening to ensure result is in given range. Needed by
1496     * submaps.
1497 dl 1.1 * @param kkey the key
1498     * @param rel the relation -- OR'ed combination of EQ, LT, GT
1499     * @param least minimum allowed key value
1500     * @param fence key greater than maximum allowed key value
1501 dl 1.2 * @param keyOnly if true return key, else return SimpleImmutableEntry
1502 dl 1.1 * @return Key or Entry fitting relation, or <tt>null</tt> if no such
1503     */
1504     Object getNear(K kkey, int rel, K least, K fence, boolean keyOnly) {
1505     K key = kkey;
1506     // Don't return keys less than least
1507     if ((rel & LT) == 0) {
1508     if (compare(key, least) < 0) {
1509     key = least;
1510     rel = rel | EQ;
1511     }
1512     }
1513    
1514     for (;;) {
1515     Node<K,V> n = findNear(key, rel);
1516     if (n == null || !inHalfOpenRange(n.key, least, fence))
1517     return null;
1518     K k = n.key;
1519     V v = n.getValidValue();
1520 dl 1.2 if (v != null) {
1521     if (keyOnly)
1522     return k;
1523     else
1524     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1525     }
1526 dl 1.1 }
1527     }
1528    
1529     /**
1530     * Find and remove least element of subrange.
1531     * @param least minimum allowed key value
1532     * @param fence key greater than maximum allowed key value
1533 dl 1.2 * @param keyOnly if true return key, else return SimpleImmutableEntry
1534 dl 1.1 * @return least Key or Entry, or <tt>null</tt> if no such
1535     */
1536     Object removeFirstEntryOfSubrange(K least, K fence, boolean keyOnly) {
1537     for (;;) {
1538     Node<K,V> n = findCeiling(least);
1539     if (n == null)
1540     return null;
1541     K k = n.key;
1542     if (fence != null && compare(k, fence) >= 0)
1543     return null;
1544     V v = doRemove(k, null);
1545 dl 1.2 if (v != null) {
1546     if (keyOnly)
1547     return k;
1548     else
1549     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1550     }
1551 dl 1.1 }
1552     }
1553    
1554     /**
1555     * Find and remove greatest element of subrange.
1556     * @param least minimum allowed key value
1557     * @param fence key greater than maximum allowed key value
1558 dl 1.2 * @param keyOnly if true return key, else return SimpleImmutableEntry
1559 dl 1.1 * @return least Key or Entry, or <tt>null</tt> if no such
1560     */
1561     Object removeLastEntryOfSubrange(K least, K fence, boolean keyOnly) {
1562     for (;;) {
1563     Node<K,V> n = findLower(fence);
1564     if (n == null)
1565     return null;
1566     K k = n.key;
1567     if (least != null && compare(k, least) < 0)
1568     return null;
1569     V v = doRemove(k, null);
1570 dl 1.2 if (v != null) {
1571     if (keyOnly)
1572     return k;
1573     else
1574     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
1575     }
1576 dl 1.1 }
1577     }
1578    
1579     /* ---------------- Constructors -------------- */
1580    
1581     /**
1582     * Constructs a new empty map, sorted according to the keys' natural
1583     * order.
1584     */
1585     public ConcurrentSkipListMap() {
1586     this.comparator = null;
1587     initialize();
1588     }
1589    
1590     /**
1591     * Constructs a new empty map, sorted according to the given comparator.
1592     *
1593     * @param c the comparator that will be used to sort this map. A
1594     * <tt>null</tt> value indicates that the keys' <i>natural
1595     * ordering</i> should be used.
1596     */
1597     public ConcurrentSkipListMap(Comparator<? super K> c) {
1598     this.comparator = c;
1599     initialize();
1600     }
1601    
1602     /**
1603     * Constructs a new map containing the same mappings as the given map,
1604     * sorted according to the keys' <i>natural order</i>.
1605     *
1606     * @param m the map whose mappings are to be placed in this map.
1607     * @throws ClassCastException if the keys in m are not Comparable, or
1608     * are not mutually comparable.
1609     * @throws NullPointerException if the specified map is <tt>null</tt>.
1610     */
1611     public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1612     this.comparator = null;
1613     initialize();
1614     putAll(m);
1615     }
1616    
1617     /**
1618     * Constructs a new map containing the same mappings as the given
1619     * <tt>SortedMap</tt>, sorted according to the same ordering.
1620     * @param m the sorted map whose mappings are to be placed in this
1621     * map, and whose comparator is to be used to sort this map.
1622     * @throws NullPointerException if the specified sorted map is
1623     * <tt>null</tt>.
1624     */
1625     public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1626     this.comparator = m.comparator();
1627     initialize();
1628     buildFromSorted(m);
1629     }
1630    
1631     /**
1632     * Returns a shallow copy of this <tt>Map</tt> instance. (The keys and
1633     * values themselves are not cloned.)
1634     *
1635     * @return a shallow copy of this Map.
1636     */
1637     public Object clone() {
1638     ConcurrentSkipListMap<K,V> clone = null;
1639     try {
1640     clone = (ConcurrentSkipListMap<K,V>) super.clone();
1641     } catch (CloneNotSupportedException e) {
1642     throw new InternalError();
1643     }
1644    
1645     clone.initialize();
1646     clone.buildFromSorted(this);
1647     return clone;
1648     }
1649    
1650     /**
1651     * Streamlined bulk insertion to initialize from elements of
1652     * given sorted map. Call only from constructor or clone
1653     * method.
1654     */
1655     private void buildFromSorted(SortedMap<K, ? extends V> map) {
1656     if (map == null)
1657     throw new NullPointerException();
1658    
1659     HeadIndex<K,V> h = head;
1660     Node<K,V> basepred = h.node;
1661    
1662     // Track the current rightmost node at each level. Uses an
1663     // ArrayList to avoid committing to initial or maximum level.
1664     ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1665    
1666     // initialize
1667     for (int i = 0; i <= h.level; ++i)
1668     preds.add(null);
1669     Index<K,V> q = h;
1670     for (int i = h.level; i > 0; --i) {
1671     preds.set(i, q);
1672     q = q.down;
1673     }
1674    
1675     Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1676     map.entrySet().iterator();
1677     while (it.hasNext()) {
1678     Map.Entry<? extends K, ? extends V> e = it.next();
1679     int j = randomLevel();
1680     if (j > h.level) j = h.level + 1;
1681     K k = e.getKey();
1682     V v = e.getValue();
1683     if (k == null || v == null)
1684     throw new NullPointerException();
1685     Node<K,V> z = new Node<K,V>(k, v, null);
1686     basepred.next = z;
1687     basepred = z;
1688     if (j > 0) {
1689     Index<K,V> idx = null;
1690     for (int i = 1; i <= j; ++i) {
1691     idx = new Index<K,V>(z, idx, null);
1692     if (i > h.level)
1693     h = new HeadIndex<K,V>(h.node, h, idx, i);
1694    
1695     if (i < preds.size()) {
1696     preds.get(i).right = idx;
1697     preds.set(i, idx);
1698     } else
1699     preds.add(idx);
1700     }
1701     }
1702     }
1703     head = h;
1704     }
1705    
1706     /* ---------------- Serialization -------------- */
1707    
1708     /**
1709     * Save the state of the <tt>Map</tt> instance to a stream.
1710     *
1711     * @serialData The key (Object) and value (Object) for each
1712     * key-value mapping represented by the Map, followed by
1713     * <tt>null</tt>. The key-value mappings are emitted in key-order
1714     * (as determined by the Comparator, or by the keys' natural
1715     * ordering if no Comparator).
1716     */
1717     private void writeObject(java.io.ObjectOutputStream s)
1718     throws java.io.IOException {
1719     // Write out the Comparator and any hidden stuff
1720     s.defaultWriteObject();
1721    
1722     // Write out keys and values (alternating)
1723     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1724     V v = n.getValidValue();
1725     if (v != null) {
1726     s.writeObject(n.key);
1727     s.writeObject(v);
1728     }
1729     }
1730     s.writeObject(null);
1731     }
1732    
1733     /**
1734     * Reconstitute the <tt>Map</tt> instance from a stream.
1735     */
1736     private void readObject(final java.io.ObjectInputStream s)
1737     throws java.io.IOException, ClassNotFoundException {
1738     // Read in the Comparator and any hidden stuff
1739     s.defaultReadObject();
1740     // Reset transients
1741     initialize();
1742    
1743     /*
1744     * This is nearly identical to buildFromSorted, but is
1745     * distinct because readObject calls can't be nicely adapted
1746     * as the kind of iterator needed by buildFromSorted. (They
1747     * can be, but doing so requires type cheats and/or creation
1748     * of adaptor classes.) It is simpler to just adapt the code.
1749     */
1750    
1751     HeadIndex<K,V> h = head;
1752     Node<K,V> basepred = h.node;
1753     ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1754     for (int i = 0; i <= h.level; ++i)
1755     preds.add(null);
1756     Index<K,V> q = h;
1757     for (int i = h.level; i > 0; --i) {
1758     preds.set(i, q);
1759     q = q.down;
1760     }
1761    
1762     for (;;) {
1763     Object k = s.readObject();
1764     if (k == null)
1765     break;
1766     Object v = s.readObject();
1767     if (v == null)
1768     throw new NullPointerException();
1769     K key = (K) k;
1770     V val = (V) v;
1771     int j = randomLevel();
1772     if (j > h.level) j = h.level + 1;
1773     Node<K,V> z = new Node<K,V>(key, val, null);
1774     basepred.next = z;
1775     basepred = z;
1776     if (j > 0) {
1777     Index<K,V> idx = null;
1778     for (int i = 1; i <= j; ++i) {
1779     idx = new Index<K,V>(z, idx, null);
1780     if (i > h.level)
1781     h = new HeadIndex<K,V>(h.node, h, idx, i);
1782    
1783     if (i < preds.size()) {
1784     preds.get(i).right = idx;
1785     preds.set(i, idx);
1786     } else
1787     preds.add(idx);
1788     }
1789     }
1790     }
1791     head = h;
1792     }
1793    
1794     /* ------ Map API methods ------ */
1795    
1796     /**
1797     * Returns <tt>true</tt> if this map contains a mapping for the specified
1798     * key.
1799     * @param key key whose presence in this map is to be tested.
1800     * @return <tt>true</tt> if this map contains a mapping for the
1801     * specified key.
1802     * @throws ClassCastException if the key cannot be compared with the keys
1803     * currently in the map.
1804     * @throws NullPointerException if the key is <tt>null</tt>.
1805     */
1806     public boolean containsKey(Object key) {
1807     return doGet(key) != null;
1808     }
1809    
1810     /**
1811     * Returns the value to which this map maps the specified key. Returns
1812     * <tt>null</tt> if the map contains no mapping for this key.
1813     *
1814     * @param key key whose associated value is to be returned.
1815     * @return the value to which this map maps the specified key, or
1816     * <tt>null</tt> if the map contains no mapping for the key.
1817     * @throws ClassCastException if the key cannot be compared with the keys
1818     * currently in the map.
1819     * @throws NullPointerException if the key is <tt>null</tt>.
1820     */
1821     public V get(Object key) {
1822     return doGet(key);
1823     }
1824    
1825     /**
1826     * Associates the specified value with the specified key in this map.
1827     * If the map previously contained a mapping for this key, the old
1828     * value is replaced.
1829     *
1830     * @param key key with which the specified value is to be associated.
1831     * @param value value to be associated with the specified key.
1832     *
1833     * @return previous value associated with specified key, or <tt>null</tt>
1834     * if there was no mapping for key.
1835     * @throws ClassCastException if the key cannot be compared with the keys
1836     * currently in the map.
1837     * @throws NullPointerException if the key or value are <tt>null</tt>.
1838     */
1839     public V put(K key, V value) {
1840     if (value == null)
1841     throw new NullPointerException();
1842     return doPut(key, value, false);
1843     }
1844    
1845     /**
1846     * Removes the mapping for this key from this Map if present.
1847     *
1848     * @param key key for which mapping should be removed
1849     * @return previous value associated with specified key, or <tt>null</tt>
1850     * if there was no mapping for key.
1851     *
1852     * @throws ClassCastException if the key cannot be compared with the keys
1853     * currently in the map.
1854     * @throws NullPointerException if the key is <tt>null</tt>.
1855     */
1856     public V remove(Object key) {
1857     return doRemove(key, null);
1858     }
1859    
1860     /**
1861     * Returns <tt>true</tt> if this map maps one or more keys to the
1862     * specified value. This operation requires time linear in the
1863     * Map size.
1864     *
1865     * @param value value whose presence in this Map is to be tested.
1866     * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1867     * <tt>false</tt> otherwise.
1868     * @throws NullPointerException if the value is <tt>null</tt>.
1869     */
1870     public boolean containsValue(Object value) {
1871     if (value == null)
1872     throw new NullPointerException();
1873     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1874     V v = n.getValidValue();
1875     if (v != null && value.equals(v))
1876     return true;
1877     }
1878     return false;
1879     }
1880    
1881     /**
1882     * Returns the number of elements in this map. If this map
1883     * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1884     * returns <tt>Integer.MAX_VALUE</tt>.
1885     *
1886     * <p>Beware that, unlike in most collections, this method is
1887     * <em>NOT</em> a constant-time operation. Because of the
1888     * asynchronous nature of these maps, determining the current
1889     * number of elements requires traversing them all to count them.
1890     * Additionally, it is possible for the size to change during
1891     * execution of this method, in which case the returned result
1892     * will be inaccurate. Thus, this method is typically not very
1893     * useful in concurrent applications.
1894     *
1895     * @return the number of elements in this map.
1896     */
1897     public int size() {
1898     long count = 0;
1899     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1900     if (n.getValidValue() != null)
1901     ++count;
1902     }
1903     return (count >= Integer.MAX_VALUE)? Integer.MAX_VALUE : (int)count;
1904     }
1905    
1906     /**
1907     * Returns <tt>true</tt> if this map contains no key-value mappings.
1908     * @return <tt>true</tt> if this map contains no key-value mappings.
1909     */
1910     public boolean isEmpty() {
1911     return findFirst() == null;
1912     }
1913    
1914     /**
1915     * Removes all mappings from this map.
1916     */
1917     public void clear() {
1918     initialize();
1919     }
1920    
1921     /**
1922     * Returns a set view of the keys contained in this map. The set is
1923     * backed by the map, so changes to the map are reflected in the set, and
1924     * vice-versa. The set supports element removal, which removes the
1925     * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
1926     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
1927     * <tt>clear</tt> operations. It does not support the <tt>add</tt> or
1928     * <tt>addAll</tt> operations.
1929     * The view's <tt>iterator</tt> is a "weakly consistent" iterator that
1930     * will never throw {@link java.util.ConcurrentModificationException},
1931     * and guarantees to traverse elements as they existed upon
1932     * construction of the iterator, and may (but is not guaranteed to)
1933     * reflect any modifications subsequent to construction.
1934     *
1935     * @return a set view of the keys contained in this map.
1936     */
1937     public Set<K> keySet() {
1938     /*
1939     * Note: Lazy intialization works here and for other views
1940     * because view classes are stateless/immutable so it doesn't
1941     * matter wrt correctness if more than one is created (which
1942     * will only rarely happen). Even so, the following idiom
1943     * conservatively ensures that the method returns the one it
1944     * created if it does so, not one created by another racing
1945     * thread.
1946     */
1947     KeySet ks = keySet;
1948     return (ks != null) ? ks : (keySet = new KeySet());
1949     }
1950    
1951     /**
1952     * Returns a set view of the keys contained in this map in
1953     * descending order. The set is backed by the map, so changes to
1954     * the map are reflected in the set, and vice-versa. The set
1955     * supports element removal, which removes the corresponding
1956     * mapping from this map, via the <tt>Iterator.remove</tt>,
1957     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>,
1958     * and <tt>clear</tt> operations. It does not support the
1959     * <tt>add</tt> or <tt>addAll</tt> operations. The view's
1960     * <tt>iterator</tt> is a "weakly consistent" iterator that will
1961     * never throw {@link java.util.ConcurrentModificationException},
1962     * and guarantees to traverse elements as they existed upon
1963     * construction of the iterator, and may (but is not guaranteed
1964     * to) reflect any modifications subsequent to construction.
1965     *
1966     * @return a set view of the keys contained in this map.
1967     */
1968     public Set<K> descendingKeySet() {
1969     /*
1970     * Note: Lazy intialization works here and for other views
1971     * because view classes are stateless/immutable so it doesn't
1972     * matter wrt correctness if more than one is created (which
1973     * will only rarely happen). Even so, the following idiom
1974     * conservatively ensures that the method returns the one it
1975     * created if it does so, not one created by another racing
1976     * thread.
1977     */
1978     DescendingKeySet ks = descendingKeySet;
1979     return (ks != null) ? ks : (descendingKeySet = new DescendingKeySet());
1980     }
1981    
1982     /**
1983     * Returns a collection view of the values contained in this map.
1984     * The collection is backed by the map, so changes to the map are
1985     * reflected in the collection, and vice-versa. The collection
1986     * supports element removal, which removes the corresponding
1987     * mapping from this map, via the <tt>Iterator.remove</tt>,
1988     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1989     * <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
1990     * support the <tt>add</tt> or <tt>addAll</tt> operations. The
1991     * view's <tt>iterator</tt> is a "weakly consistent" iterator that
1992     * will never throw {@link
1993     * java.util.ConcurrentModificationException}, and guarantees to
1994     * traverse elements as they existed upon construction of the
1995     * iterator, and may (but is not guaranteed to) reflect any
1996     * modifications subsequent to construction.
1997     *
1998     * @return a collection view of the values contained in this map.
1999     */
2000     public Collection<V> values() {
2001     Values vs = values;
2002     return (vs != null) ? vs : (values = new Values());
2003     }
2004    
2005     /**
2006     * Returns a collection view of the mappings contained in this
2007     * map. Each element in the returned collection is a
2008     * <tt>Map.Entry</tt>. The collection is backed by the map, so
2009     * changes to the map are reflected in the collection, and
2010     * vice-versa. The collection supports element removal, which
2011     * removes the corresponding mapping from the map, via the
2012     * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
2013     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
2014     * operations. It does not support the <tt>add</tt> or
2015     * <tt>addAll</tt> operations. The view's <tt>iterator</tt> is a
2016     * "weakly consistent" iterator that will never throw {@link
2017     * java.util.ConcurrentModificationException}, and guarantees to
2018     * traverse elements as they existed upon construction of the
2019     * iterator, and may (but is not guaranteed to) reflect any
2020     * modifications subsequent to construction. The
2021     * <tt>Map.Entry</tt> elements returned by
2022     * <tt>iterator.next()</tt> do <em>not</em> support the
2023     * <tt>setValue</tt> operation.
2024     *
2025     * @return a collection view of the mappings contained in this map.
2026     */
2027     public Set<Map.Entry<K,V>> entrySet() {
2028     EntrySet es = entrySet;
2029     return (es != null) ? es : (entrySet = new EntrySet());
2030     }
2031    
2032     /**
2033     * Returns a collection view of the mappings contained in this
2034     * map, in descending order. Each element in the returned
2035     * collection is a <tt>Map.Entry</tt>. The collection is backed
2036     * by the map, so changes to the map are reflected in the
2037     * collection, and vice-versa. The collection supports element
2038     * removal, which removes the corresponding mapping from the map,
2039     * via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
2040     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
2041     * operations. It does not support the <tt>add</tt> or
2042     * <tt>addAll</tt> operations. The view's <tt>iterator</tt> is a
2043     * "weakly consistent" iterator that will never throw {@link
2044     * java.util.ConcurrentModificationException}, and guarantees to
2045     * traverse elements as they existed upon construction of the
2046     * iterator, and may (but is not guaranteed to) reflect any
2047     * modifications subsequent to construction. The
2048     * <tt>Map.Entry</tt> elements returned by
2049     * <tt>iterator.next()</tt> do <em>not</em> support the
2050     * <tt>setValue</tt> operation.
2051     *
2052     * @return a collection view of the mappings contained in this map.
2053     */
2054     public Set<Map.Entry<K,V>> descendingEntrySet() {
2055     DescendingEntrySet es = descendingEntrySet;
2056     return (es != null) ? es : (descendingEntrySet = new DescendingEntrySet());
2057     }
2058    
2059     /* ---------------- AbstractMap Overrides -------------- */
2060    
2061     /**
2062     * Compares the specified object with this map for equality.
2063     * Returns <tt>true</tt> if the given object is also a map and the
2064     * two maps represent the same mappings. More formally, two maps
2065     * <tt>t1</tt> and <tt>t2</tt> represent the same mappings if
2066     * <tt>t1.keySet().equals(t2.keySet())</tt> and for every key
2067     * <tt>k</tt> in <tt>t1.keySet()</tt>, <tt> (t1.get(k)==null ?
2068     * t2.get(k)==null : t1.get(k).equals(t2.get(k))) </tt>. This
2069     * operation may return misleading results if either map is
2070     * concurrently modified during execution of this method.
2071     *
2072     * @param o object to be compared for equality with this map.
2073     * @return <tt>true</tt> if the specified object is equal to this map.
2074     */
2075     public boolean equals(Object o) {
2076     if (o == this)
2077     return true;
2078     if (!(o instanceof Map))
2079     return false;
2080     Map<K,V> t = (Map<K,V>) o;
2081     try {
2082     return (containsAllMappings(this, t) &&
2083     containsAllMappings(t, this));
2084     } catch(ClassCastException unused) {
2085     return false;
2086     } catch(NullPointerException unused) {
2087     return false;
2088     }
2089     }
2090    
2091     /**
2092     * Helper for equals -- check for containment, avoiding nulls.
2093     */
2094     static <K,V> boolean containsAllMappings(Map<K,V> a, Map<K,V> b) {
2095     Iterator<Entry<K,V>> it = b.entrySet().iterator();
2096     while (it.hasNext()) {
2097     Entry<K,V> e = it.next();
2098     Object k = e.getKey();
2099     Object v = e.getValue();
2100     if (k == null || v == null || !v.equals(a.get(k)))
2101     return false;
2102     }
2103     return true;
2104     }
2105    
2106     /* ------ ConcurrentMap API methods ------ */
2107    
2108     /**
2109     * If the specified key is not already associated
2110     * with a value, associate it with the given value.
2111     * This is equivalent to
2112     * <pre>
2113     * if (!map.containsKey(key))
2114     * return map.put(key, value);
2115     * else
2116     * return map.get(key);
2117     * </pre>
2118     * except that the action is performed atomically.
2119     * @param key key with which the specified value is to be associated.
2120     * @param value value to be associated with the specified key.
2121     * @return previous value associated with specified key, or <tt>null</tt>
2122     * if there was no mapping for key.
2123     *
2124     * @throws ClassCastException if the key cannot be compared with the keys
2125     * currently in the map.
2126     * @throws NullPointerException if the key or value are <tt>null</tt>.
2127     */
2128     public V putIfAbsent(K key, V value) {
2129     if (value == null)
2130     throw new NullPointerException();
2131     return doPut(key, value, true);
2132     }
2133    
2134     /**
2135     * Remove entry for key only if currently mapped to given value.
2136     * Acts as
2137     * <pre>
2138     * if ((map.containsKey(key) && map.get(key).equals(value)) {
2139     * map.remove(key);
2140     * return true;
2141     * } else return false;
2142     * </pre>
2143     * except that the action is performed atomically.
2144     * @param key key with which the specified value is associated.
2145     * @param value value associated with the specified key.
2146     * @return true if the value was removed, false otherwise
2147     * @throws ClassCastException if the key cannot be compared with the keys
2148     * currently in the map.
2149     * @throws NullPointerException if the key or value are <tt>null</tt>.
2150     */
2151     public boolean remove(Object key, Object value) {
2152     if (value == null)
2153     throw new NullPointerException();
2154     return doRemove(key, value) != null;
2155     }
2156    
2157     /**
2158     * Replace entry for key only if currently mapped to given value.
2159     * Acts as
2160     * <pre>
2161     * if ((map.containsKey(key) && map.get(key).equals(oldValue)) {
2162     * map.put(key, newValue);
2163     * return true;
2164     * } else return false;
2165     * </pre>
2166     * except that the action is performed atomically.
2167     * @param key key with which the specified value is associated.
2168     * @param oldValue value expected to be associated with the specified key.
2169     * @param newValue value to be associated with the specified key.
2170     * @return true if the value was replaced
2171     * @throws ClassCastException if the key cannot be compared with the keys
2172     * currently in the map.
2173     * @throws NullPointerException if key, oldValue or newValue are
2174     * <tt>null</tt>.
2175     */
2176     public boolean replace(K key, V oldValue, V newValue) {
2177     if (oldValue == null || newValue == null)
2178     throw new NullPointerException();
2179     Comparable<K> k = comparable(key);
2180     for (;;) {
2181     Node<K,V> n = findNode(k);
2182     if (n == null)
2183     return false;
2184     Object v = n.value;
2185     if (v != null) {
2186     if (!oldValue.equals(v))
2187     return false;
2188     if (n.casValue(v, newValue))
2189     return true;
2190     }
2191     }
2192     }
2193    
2194     /**
2195     * Replace entry for key only if currently mapped to some value.
2196     * Acts as
2197     * <pre>
2198     * if ((map.containsKey(key)) {
2199     * return map.put(key, value);
2200     * } else return null;
2201     * </pre>
2202     * except that the action is performed atomically.
2203     * @param key key with which the specified value is associated.
2204     * @param value value to be associated with the specified key.
2205     * @return previous value associated with specified key, or <tt>null</tt>
2206     * if there was no mapping for key.
2207     * @throws ClassCastException if the key cannot be compared with the keys
2208     * currently in the map.
2209     * @throws NullPointerException if the key or value are <tt>null</tt>.
2210     */
2211     public V replace(K key, V value) {
2212     if (value == null)
2213     throw new NullPointerException();
2214     Comparable<K> k = comparable(key);
2215     for (;;) {
2216     Node<K,V> n = findNode(k);
2217     if (n == null)
2218     return null;
2219     Object v = n.value;
2220     if (v != null && n.casValue(v, value))
2221     return (V)v;
2222     }
2223     }
2224    
2225     /* ------ SortedMap API methods ------ */
2226    
2227     /**
2228     * Returns the comparator used to order this map, or <tt>null</tt>
2229     * if this map uses its keys' natural order.
2230     *
2231     * @return the comparator associated with this map, or
2232     * <tt>null</tt> if it uses its keys' natural sort method.
2233     */
2234     public Comparator<? super K> comparator() {
2235     return comparator;
2236     }
2237    
2238     /**
2239     * Returns the first (lowest) key currently in this map.
2240     *
2241     * @return the first (lowest) key currently in this map.
2242     * @throws NoSuchElementException Map is empty.
2243     */
2244     public K firstKey() {
2245     Node<K,V> n = findFirst();
2246     if (n == null)
2247     throw new NoSuchElementException();
2248     return n.key;
2249     }
2250    
2251     /**
2252     * Returns the last (highest) key currently in this map.
2253     *
2254     * @return the last (highest) key currently in this map.
2255     * @throws NoSuchElementException Map is empty.
2256     */
2257     public K lastKey() {
2258     Node<K,V> n = findLast();
2259     if (n == null)
2260     throw new NoSuchElementException();
2261     return n.key;
2262     }
2263    
2264     /**
2265     * Returns a view of the portion of this map whose keys range from
2266     * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive. (If
2267     * <tt>fromKey</tt> and <tt>toKey</tt> are equal, the returned sorted map
2268     * is empty.) The returned sorted map is backed by this map, so changes
2269     * in the returned sorted map are reflected in this map, and vice-versa.
2270    
2271     * @param fromKey low endpoint (inclusive) of the subMap.
2272     * @param toKey high endpoint (exclusive) of the subMap.
2273     *
2274     * @return a view of the portion of this map whose keys range from
2275     * <tt>fromKey</tt>, inclusive, to <tt>toKey</tt>, exclusive.
2276     *
2277     * @throws ClassCastException if <tt>fromKey</tt> and <tt>toKey</tt>
2278     * cannot be compared to one another using this map's comparator
2279     * (or, if the map has no comparator, using natural ordering).
2280     * @throws IllegalArgumentException if <tt>fromKey</tt> is greater than
2281     * <tt>toKey</tt>.
2282     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is
2283     * <tt>null</tt>.
2284     */
2285     public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2286     if (fromKey == null || toKey == null)
2287     throw new NullPointerException();
2288     return new ConcurrentSkipListSubMap(this, fromKey, toKey);
2289     }
2290    
2291     /**
2292     * Returns a view of the portion of this map whose keys are
2293     * strictly less than <tt>toKey</tt>. The returned sorted map is
2294     * backed by this map, so changes in the returned sorted map are
2295     * reflected in this map, and vice-versa.
2296     * @param toKey high endpoint (exclusive) of the headMap.
2297     * @return a view of the portion of this map whose keys are
2298     * strictly less than <tt>toKey</tt>.
2299     *
2300     * @throws ClassCastException if <tt>toKey</tt> is not compatible
2301     * with this map's comparator (or, if the map has no comparator,
2302     * if <tt>toKey</tt> does not implement <tt>Comparable</tt>).
2303     * @throws NullPointerException if <tt>toKey</tt> is <tt>null</tt>.
2304     */
2305     public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2306     if (toKey == null)
2307     throw new NullPointerException();
2308     return new ConcurrentSkipListSubMap(this, null, toKey);
2309     }
2310    
2311     /**
2312     * Returns a view of the portion of this map whose keys are
2313     * greater than or equal to <tt>fromKey</tt>. The returned sorted
2314     * map is backed by this map, so changes in the returned sorted
2315     * map are reflected in this map, and vice-versa.
2316     * @param fromKey low endpoint (inclusive) of the tailMap.
2317     * @return a view of the portion of this map whose keys are
2318     * greater than or equal to <tt>fromKey</tt>.
2319     * @throws ClassCastException if <tt>fromKey</tt> is not
2320     * compatible with this map's comparator (or, if the map has no
2321     * comparator, if <tt>fromKey</tt> does not implement
2322     * <tt>Comparable</tt>).
2323     * @throws NullPointerException if <tt>fromKey</tt> is <tt>null</tt>.
2324     */
2325     public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2326     if (fromKey == null)
2327     throw new NullPointerException();
2328     return new ConcurrentSkipListSubMap(this, fromKey, null);
2329     }
2330    
2331     /* ---------------- Relational operations -------------- */
2332    
2333     /**
2334     * Returns a key-value mapping associated with the least key
2335     * greater than or equal to the given key, or <tt>null</tt> if
2336     * there is no such entry. The returned entry does <em>not</em>
2337     * support the <tt>Entry.setValue</tt> method.
2338     *
2339     * @param key the key.
2340     * @return an Entry associated with ceiling of given key, or
2341     * <tt>null</tt> if there is no such Entry.
2342     * @throws ClassCastException if key cannot be compared with the
2343     * keys currently in the map.
2344     * @throws NullPointerException if key is <tt>null</tt>.
2345     */
2346     public Map.Entry<K,V> ceilingEntry(K key) {
2347     return getNear(key, GT|EQ);
2348     }
2349    
2350     /**
2351     * Returns least key greater than or equal to the given key, or
2352     * <tt>null</tt> if there is no such key.
2353     *
2354     * @param key the key.
2355     * @return the ceiling key, or <tt>null</tt>
2356     * if there is no such key.
2357     * @throws ClassCastException if key cannot be compared with the keys
2358     * currently in the map.
2359     * @throws NullPointerException if key is <tt>null</tt>.
2360     */
2361     public K ceilingKey(K key) {
2362     Node<K,V> n = findNear(key, GT|EQ);
2363     return (n == null)? null : n.key;
2364     }
2365    
2366     /**
2367     * Returns a key-value mapping associated with the greatest
2368     * key strictly less than the given key, or <tt>null</tt> if there is no
2369     * such entry. The returned entry does <em>not</em> support
2370     * the <tt>Entry.setValue</tt> method.
2371     *
2372     * @param key the key.
2373     * @return an Entry with greatest key less than the given
2374     * key, or <tt>null</tt> if there is no such Entry.
2375     * @throws ClassCastException if key cannot be compared with the keys
2376     * currently in the map.
2377     * @throws NullPointerException if key is <tt>null</tt>.
2378     */
2379     public Map.Entry<K,V> lowerEntry(K key) {
2380     return getNear(key, LT);
2381     }
2382    
2383     /**
2384     * Returns the greatest key strictly less than the given key, or
2385     * <tt>null</tt> if there is no such key.
2386     *
2387     * @param key the key.
2388     * @return the greatest key less than the given
2389     * key, or <tt>null</tt> if there is no such key.
2390     * @throws ClassCastException if key cannot be compared with the keys
2391     * currently in the map.
2392     * @throws NullPointerException if key is <tt>null</tt>.
2393     */
2394     public K lowerKey(K key) {
2395     Node<K,V> n = findNear(key, LT);
2396     return (n == null)? null : n.key;
2397     }
2398    
2399     /**
2400     * Returns a key-value mapping associated with the greatest key
2401     * less than or equal to the given key, or <tt>null</tt> if there
2402     * is no such entry. The returned entry does <em>not</em> support
2403     * the <tt>Entry.setValue</tt> method.
2404     *
2405     * @param key the key.
2406     * @return an Entry associated with floor of given key, or <tt>null</tt>
2407     * if there is no such Entry.
2408     * @throws ClassCastException if key cannot be compared with the keys
2409     * currently in the map.
2410     * @throws NullPointerException if key is <tt>null</tt>.
2411     */
2412     public Map.Entry<K,V> floorEntry(K key) {
2413     return getNear(key, LT|EQ);
2414     }
2415    
2416     /**
2417     * Returns the greatest key
2418     * less than or equal to the given key, or <tt>null</tt> if there
2419     * is no such key.
2420     *
2421     * @param key the key.
2422     * @return the floor of given key, or <tt>null</tt> if there is no
2423     * such key.
2424     * @throws ClassCastException if key cannot be compared with the keys
2425     * currently in the map.
2426     * @throws NullPointerException if key is <tt>null</tt>.
2427     */
2428     public K floorKey(K key) {
2429     Node<K,V> n = findNear(key, LT|EQ);
2430     return (n == null)? null : n.key;
2431     }
2432    
2433     /**
2434     * Returns a key-value mapping associated with the least key
2435     * strictly greater than the given key, or <tt>null</tt> if there
2436     * is no such entry. The returned entry does <em>not</em> support
2437     * the <tt>Entry.setValue</tt> method.
2438     *
2439     * @param key the key.
2440     * @return an Entry with least key greater than the given key, or
2441     * <tt>null</tt> if there is no such Entry.
2442     * @throws ClassCastException if key cannot be compared with the keys
2443     * currently in the map.
2444     * @throws NullPointerException if key is <tt>null</tt>.
2445     */
2446     public Map.Entry<K,V> higherEntry(K key) {
2447     return getNear(key, GT);
2448     }
2449    
2450     /**
2451     * Returns the least key strictly greater than the given key, or
2452     * <tt>null</tt> if there is no such key.
2453     *
2454     * @param key the key.
2455     * @return the least key greater than the given key, or
2456     * <tt>null</tt> if there is no such key.
2457     * @throws ClassCastException if key cannot be compared with the keys
2458     * currently in the map.
2459     * @throws NullPointerException if key is <tt>null</tt>.
2460     */
2461     public K higherKey(K key) {
2462     Node<K,V> n = findNear(key, GT);
2463     return (n == null)? null : n.key;
2464     }
2465    
2466     /**
2467     * Returns a key-value mapping associated with the least
2468     * key in this map, or <tt>null</tt> if the map is empty.
2469     * The returned entry does <em>not</em> support
2470     * the <tt>Entry.setValue</tt> method.
2471     *
2472     * @return an Entry with least key, or <tt>null</tt>
2473     * if the map is empty.
2474     */
2475     public Map.Entry<K,V> firstEntry() {
2476     for (;;) {
2477     Node<K,V> n = findFirst();
2478     if (n == null)
2479     return null;
2480 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2481 dl 1.1 if (e != null)
2482     return e;
2483     }
2484     }
2485    
2486     /**
2487     * Returns a key-value mapping associated with the greatest
2488     * key in this map, or <tt>null</tt> if the map is empty.
2489     * The returned entry does <em>not</em> support
2490     * the <tt>Entry.setValue</tt> method.
2491     *
2492     * @return an Entry with greatest key, or <tt>null</tt>
2493     * if the map is empty.
2494     */
2495     public Map.Entry<K,V> lastEntry() {
2496     for (;;) {
2497     Node<K,V> n = findLast();
2498     if (n == null)
2499     return null;
2500 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2501 dl 1.1 if (e != null)
2502     return e;
2503     }
2504     }
2505    
2506     /**
2507     * Removes and returns a key-value mapping associated with
2508     * the least key in this map, or <tt>null</tt> if the map is empty.
2509     * The returned entry does <em>not</em> support
2510     * the <tt>Entry.setValue</tt> method.
2511     *
2512     * @return the removed first entry of this map, or <tt>null</tt>
2513     * if the map is empty.
2514     */
2515     public Map.Entry<K,V> pollFirstEntry() {
2516 dl 1.2 return (AbstractMap.SimpleImmutableEntry<K,V>)doRemoveFirst(false);
2517 dl 1.1 }
2518    
2519     /**
2520     * Removes and returns a key-value mapping associated with
2521     * the greatest key in this map, or <tt>null</tt> if the map is empty.
2522     * The returned entry does <em>not</em> support
2523     * the <tt>Entry.setValue</tt> method.
2524     *
2525     * @return the removed last entry of this map, or <tt>null</tt>
2526     * if the map is empty.
2527     */
2528     public Map.Entry<K,V> pollLastEntry() {
2529 dl 1.2 return (AbstractMap.SimpleImmutableEntry<K,V>)doRemoveLast(false);
2530 dl 1.1 }
2531    
2532    
2533     /* ---------------- Iterators -------------- */
2534    
2535     /**
2536     * Base of ten kinds of iterator classes:
2537     * ascending: {map, submap} X {key, value, entry}
2538     * descending: {map, submap} X {key, entry}
2539     */
2540     abstract class Iter {
2541     /** the last node returned by next() */
2542     Node<K,V> last;
2543     /** the next node to return from next(); */
2544     Node<K,V> next;
2545     /** Cache of next value field to maintain weak consistency */
2546     Object nextValue;
2547    
2548     Iter() {}
2549    
2550     public final boolean hasNext() {
2551     return next != null;
2552     }
2553    
2554     /** initialize ascending iterator for entire range */
2555     final void initAscending() {
2556     for (;;) {
2557     next = findFirst();
2558     if (next == null)
2559     break;
2560     nextValue = next.value;
2561     if (nextValue != null && nextValue != next)
2562     break;
2563     }
2564     }
2565    
2566     /**
2567     * initialize ascending iterator starting at given least key,
2568     * or first node if least is <tt>null</tt>, but not greater or
2569     * equal to fence, or end if fence is <tt>null</tt>.
2570     */
2571     final void initAscending(K least, K fence) {
2572     for (;;) {
2573     next = findCeiling(least);
2574     if (next == null)
2575     break;
2576     nextValue = next.value;
2577     if (nextValue != null && nextValue != next) {
2578     if (fence != null && compare(fence, next.key) <= 0) {
2579     next = null;
2580     nextValue = null;
2581     }
2582     break;
2583     }
2584     }
2585     }
2586     /** advance next to higher entry */
2587     final void ascend() {
2588     if ((last = next) == null)
2589     throw new NoSuchElementException();
2590     for (;;) {
2591     next = next.next;
2592     if (next == null)
2593     break;
2594     nextValue = next.value;
2595     if (nextValue != null && nextValue != next)
2596     break;
2597     }
2598     }
2599    
2600     /**
2601     * Version of ascend for submaps to stop at fence
2602     */
2603     final void ascend(K fence) {
2604     if ((last = next) == null)
2605     throw new NoSuchElementException();
2606     for (;;) {
2607     next = next.next;
2608     if (next == null)
2609     break;
2610     nextValue = next.value;
2611     if (nextValue != null && nextValue != next) {
2612     if (fence != null && compare(fence, next.key) <= 0) {
2613     next = null;
2614     nextValue = null;
2615     }
2616     break;
2617     }
2618     }
2619     }
2620    
2621     /** initialize descending iterator for entire range */
2622     final void initDescending() {
2623     for (;;) {
2624     next = findLast();
2625     if (next == null)
2626     break;
2627     nextValue = next.value;
2628     if (nextValue != null && nextValue != next)
2629     break;
2630     }
2631     }
2632    
2633     /**
2634     * initialize descending iterator starting at key less
2635     * than or equal to given fence key, or
2636     * last node if fence is <tt>null</tt>, but not less than
2637     * least, or beginning if lest is <tt>null</tt>.
2638     */
2639     final void initDescending(K least, K fence) {
2640     for (;;) {
2641     next = findLower(fence);
2642     if (next == null)
2643     break;
2644     nextValue = next.value;
2645     if (nextValue != null && nextValue != next) {
2646     if (least != null && compare(least, next.key) > 0) {
2647     next = null;
2648     nextValue = null;
2649     }
2650     break;
2651     }
2652     }
2653     }
2654    
2655     /** advance next to lower entry */
2656     final void descend() {
2657     if ((last = next) == null)
2658     throw new NoSuchElementException();
2659     K k = last.key;
2660     for (;;) {
2661     next = findNear(k, LT);
2662     if (next == null)
2663     break;
2664     nextValue = next.value;
2665     if (nextValue != null && nextValue != next)
2666     break;
2667     }
2668     }
2669    
2670     /**
2671     * Version of descend for submaps to stop at least
2672     */
2673     final void descend(K least) {
2674     if ((last = next) == null)
2675     throw new NoSuchElementException();
2676     K k = last.key;
2677     for (;;) {
2678     next = findNear(k, LT);
2679     if (next == null)
2680     break;
2681     nextValue = next.value;
2682     if (nextValue != null && nextValue != next) {
2683     if (least != null && compare(least, next.key) > 0) {
2684     next = null;
2685     nextValue = null;
2686     }
2687     break;
2688     }
2689     }
2690     }
2691    
2692     public void remove() {
2693     Node<K,V> l = last;
2694     if (l == null)
2695     throw new IllegalStateException();
2696     // It would not be worth all of the overhead to directly
2697     // unlink from here. Using remove is fast enough.
2698     ConcurrentSkipListMap.this.remove(l.key);
2699     }
2700    
2701     }
2702    
2703     final class ValueIterator extends Iter implements Iterator<V> {
2704     ValueIterator() {
2705     initAscending();
2706     }
2707     public V next() {
2708     Object v = nextValue;
2709     ascend();
2710     return (V)v;
2711     }
2712     }
2713    
2714     final class KeyIterator extends Iter implements Iterator<K> {
2715     KeyIterator() {
2716     initAscending();
2717     }
2718     public K next() {
2719     Node<K,V> n = next;
2720     ascend();
2721     return n.key;
2722     }
2723     }
2724    
2725     class SubMapValueIterator extends Iter implements Iterator<V> {
2726     final K fence;
2727     SubMapValueIterator(K least, K fence) {
2728     initAscending(least, fence);
2729     this.fence = fence;
2730     }
2731    
2732     public V next() {
2733     Object v = nextValue;
2734     ascend(fence);
2735     return (V)v;
2736     }
2737     }
2738    
2739     final class SubMapKeyIterator extends Iter implements Iterator<K> {
2740     final K fence;
2741     SubMapKeyIterator(K least, K fence) {
2742     initAscending(least, fence);
2743     this.fence = fence;
2744     }
2745    
2746     public K next() {
2747     Node<K,V> n = next;
2748     ascend(fence);
2749     return n.key;
2750     }
2751     }
2752    
2753     final class DescendingKeyIterator extends Iter implements Iterator<K> {
2754     DescendingKeyIterator() {
2755     initDescending();
2756     }
2757     public K next() {
2758     Node<K,V> n = next;
2759     descend();
2760     return n.key;
2761     }
2762     }
2763    
2764     final class DescendingSubMapKeyIterator extends Iter implements Iterator<K> {
2765     final K least;
2766     DescendingSubMapKeyIterator(K least, K fence) {
2767     initDescending(least, fence);
2768     this.least = least;
2769     }
2770    
2771     public K next() {
2772     Node<K,V> n = next;
2773     descend(least);
2774     return n.key;
2775     }
2776     }
2777    
2778     /**
2779     * Entry iterators use the same trick as in ConcurrentHashMap and
2780     * elsewhere of using the iterator itself to represent entries,
2781     * thus avoiding having to create entry objects in next().
2782     */
2783     abstract class EntryIter extends Iter implements Map.Entry<K,V> {
2784     /** Cache of last value returned */
2785     Object lastValue;
2786    
2787     EntryIter() {
2788     }
2789    
2790     public K getKey() {
2791     Node<K,V> l = last;
2792     if (l == null)
2793     throw new IllegalStateException();
2794     return l.key;
2795     }
2796    
2797     public V getValue() {
2798     Object v = lastValue;
2799     if (last == null || v == null)
2800     throw new IllegalStateException();
2801     return (V)v;
2802     }
2803    
2804     public V setValue(V value) {
2805     throw new UnsupportedOperationException();
2806     }
2807    
2808     public boolean equals(Object o) {
2809     // If not acting as entry, just use default.
2810     if (last == null)
2811     return super.equals(o);
2812     if (!(o instanceof Map.Entry))
2813     return false;
2814     Map.Entry e = (Map.Entry)o;
2815     return (getKey().equals(e.getKey()) &&
2816     getValue().equals(e.getValue()));
2817     }
2818    
2819     public int hashCode() {
2820     // If not acting as entry, just use default.
2821     if (last == null)
2822     return super.hashCode();
2823     return getKey().hashCode() ^ getValue().hashCode();
2824     }
2825    
2826     public String toString() {
2827     // If not acting as entry, just use default.
2828     if (last == null)
2829     return super.toString();
2830     return getKey() + "=" + getValue();
2831     }
2832     }
2833    
2834     final class EntryIterator extends EntryIter
2835     implements Iterator<Map.Entry<K,V>> {
2836     EntryIterator() {
2837     initAscending();
2838     }
2839     public Map.Entry<K,V> next() {
2840     lastValue = nextValue;
2841     ascend();
2842     return this;
2843     }
2844     }
2845    
2846     final class SubMapEntryIterator extends EntryIter
2847     implements Iterator<Map.Entry<K,V>> {
2848     final K fence;
2849     SubMapEntryIterator(K least, K fence) {
2850     initAscending(least, fence);
2851     this.fence = fence;
2852     }
2853    
2854     public Map.Entry<K,V> next() {
2855     lastValue = nextValue;
2856     ascend(fence);
2857     return this;
2858     }
2859     }
2860    
2861     final class DescendingEntryIterator extends EntryIter
2862     implements Iterator<Map.Entry<K,V>> {
2863     DescendingEntryIterator() {
2864     initDescending();
2865     }
2866     public Map.Entry<K,V> next() {
2867     lastValue = nextValue;
2868     descend();
2869     return this;
2870     }
2871     }
2872    
2873     final class DescendingSubMapEntryIterator extends EntryIter
2874     implements Iterator<Map.Entry<K,V>> {
2875     final K least;
2876     DescendingSubMapEntryIterator(K least, K fence) {
2877     initDescending(least, fence);
2878     this.least = least;
2879     }
2880    
2881     public Map.Entry<K,V> next() {
2882     lastValue = nextValue;
2883     descend(least);
2884     return this;
2885     }
2886     }
2887    
2888     // Factory methods for iterators needed by submaps and/or
2889     // ConcurrentSkipListSet
2890    
2891     Iterator<K> keyIterator() {
2892     return new KeyIterator();
2893     }
2894    
2895     Iterator<K> descendingKeyIterator() {
2896     return new DescendingKeyIterator();
2897     }
2898    
2899     SubMapEntryIterator subMapEntryIterator(K least, K fence) {
2900     return new SubMapEntryIterator(least, fence);
2901     }
2902    
2903     DescendingSubMapEntryIterator descendingSubMapEntryIterator(K least, K fence) {
2904     return new DescendingSubMapEntryIterator(least, fence);
2905     }
2906    
2907     SubMapKeyIterator subMapKeyIterator(K least, K fence) {
2908     return new SubMapKeyIterator(least, fence);
2909     }
2910    
2911     DescendingSubMapKeyIterator descendingSubMapKeyIterator(K least, K fence) {
2912     return new DescendingSubMapKeyIterator(least, fence);
2913     }
2914    
2915     SubMapValueIterator subMapValueIterator(K least, K fence) {
2916     return new SubMapValueIterator(least, fence);
2917     }
2918    
2919     /* ---------------- Views -------------- */
2920    
2921     class KeySet extends AbstractSet<K> {
2922     public Iterator<K> iterator() {
2923     return new KeyIterator();
2924     }
2925     public boolean isEmpty() {
2926     return ConcurrentSkipListMap.this.isEmpty();
2927     }
2928     public int size() {
2929     return ConcurrentSkipListMap.this.size();
2930     }
2931     public boolean contains(Object o) {
2932     return ConcurrentSkipListMap.this.containsKey(o);
2933     }
2934     public boolean remove(Object o) {
2935     return ConcurrentSkipListMap.this.removep(o);
2936     }
2937     public void clear() {
2938     ConcurrentSkipListMap.this.clear();
2939     }
2940     public Object[] toArray() {
2941     Collection<K> c = new ArrayList<K>();
2942     for (Iterator<K> i = iterator(); i.hasNext(); )
2943     c.add(i.next());
2944     return c.toArray();
2945     }
2946     public <T> T[] toArray(T[] a) {
2947     Collection<K> c = new ArrayList<K>();
2948     for (Iterator<K> i = iterator(); i.hasNext(); )
2949     c.add(i.next());
2950     return c.toArray(a);
2951     }
2952     }
2953    
2954     class DescendingKeySet extends KeySet {
2955     public Iterator<K> iterator() {
2956     return new DescendingKeyIterator();
2957     }
2958     }
2959    
2960     final class Values extends AbstractCollection<V> {
2961     public Iterator<V> iterator() {
2962     return new ValueIterator();
2963     }
2964     public boolean isEmpty() {
2965     return ConcurrentSkipListMap.this.isEmpty();
2966     }
2967     public int size() {
2968     return ConcurrentSkipListMap.this.size();
2969     }
2970     public boolean contains(Object o) {
2971     return ConcurrentSkipListMap.this.containsValue(o);
2972     }
2973     public void clear() {
2974     ConcurrentSkipListMap.this.clear();
2975     }
2976     public Object[] toArray() {
2977     Collection<V> c = new ArrayList<V>();
2978     for (Iterator<V> i = iterator(); i.hasNext(); )
2979     c.add(i.next());
2980     return c.toArray();
2981     }
2982     public <T> T[] toArray(T[] a) {
2983     Collection<V> c = new ArrayList<V>();
2984     for (Iterator<V> i = iterator(); i.hasNext(); )
2985     c.add(i.next());
2986     return c.toArray(a);
2987     }
2988     }
2989    
2990     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
2991     public Iterator<Map.Entry<K,V>> iterator() {
2992     return new EntryIterator();
2993     }
2994     public boolean contains(Object o) {
2995     if (!(o instanceof Map.Entry))
2996     return false;
2997     Map.Entry<K,V> e = (Map.Entry<K,V>)o;
2998     V v = ConcurrentSkipListMap.this.get(e.getKey());
2999     return v != null && v.equals(e.getValue());
3000     }
3001     public boolean remove(Object o) {
3002     if (!(o instanceof Map.Entry))
3003     return false;
3004     Map.Entry<K,V> e = (Map.Entry<K,V>)o;
3005     return ConcurrentSkipListMap.this.remove(e.getKey(),
3006     e.getValue());
3007     }
3008     public boolean isEmpty() {
3009     return ConcurrentSkipListMap.this.isEmpty();
3010     }
3011     public int size() {
3012     return ConcurrentSkipListMap.this.size();
3013     }
3014     public void clear() {
3015     ConcurrentSkipListMap.this.clear();
3016     }
3017    
3018     public Object[] toArray() {
3019     Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3020     for (Map.Entry e : this)
3021 dl 1.2 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3022 dl 1.1 return c.toArray();
3023     }
3024     public <T> T[] toArray(T[] a) {
3025     Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3026     for (Map.Entry e : this)
3027 dl 1.2 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3028 dl 1.1 return c.toArray(a);
3029     }
3030     }
3031    
3032     class DescendingEntrySet extends EntrySet {
3033     public Iterator<Map.Entry<K,V>> iterator() {
3034     return new DescendingEntryIterator();
3035     }
3036     }
3037    
3038     /**
3039     * Submaps returned by {@link ConcurrentSkipListMap} submap operations
3040     * represent a subrange of mappings of their underlying
3041     * maps. Instances of this class support all methods of their
3042     * underlying maps, differing in that mappings outside their range are
3043     * ignored, and attempts to add mappings outside their ranges result
3044     * in {@link IllegalArgumentException}. Instances of this class are
3045     * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
3046     * <tt>tailMap</tt> methods of their underlying maps.
3047     */
3048     static class ConcurrentSkipListSubMap<K,V> extends AbstractMap<K,V>
3049     implements ConcurrentNavigableMap<K,V>, java.io.Serializable {
3050    
3051     private static final long serialVersionUID = -7647078645895051609L;
3052    
3053     /** Underlying map */
3054     private final ConcurrentSkipListMap<K,V> m;
3055     /** lower bound key, or null if from start */
3056     private final K least;
3057     /** upper fence key, or null if to end */
3058     private final K fence;
3059     // Lazily initialized view holders
3060     private transient Set<K> keySetView;
3061     private transient Set<Map.Entry<K,V>> entrySetView;
3062     private transient Collection<V> valuesView;
3063     private transient Set<K> descendingKeySetView;
3064     private transient Set<Map.Entry<K,V>> descendingEntrySetView;
3065    
3066     /**
3067     * Creates a new submap.
3068     * @param least inclusive least value, or <tt>null</tt> if from start
3069     * @param fence exclusive upper bound or <tt>null</tt> if to end
3070     * @throws IllegalArgumentException if least and fence nonnull
3071     * and least greater than fence
3072     */
3073     ConcurrentSkipListSubMap(ConcurrentSkipListMap<K,V> map,
3074     K least, K fence) {
3075     if (least != null &&
3076     fence != null &&
3077     map.compare(least, fence) > 0)
3078     throw new IllegalArgumentException("inconsistent range");
3079     this.m = map;
3080     this.least = least;
3081     this.fence = fence;
3082     }
3083    
3084     /* ---------------- Utilities -------------- */
3085    
3086     boolean inHalfOpenRange(K key) {
3087     return m.inHalfOpenRange(key, least, fence);
3088     }
3089    
3090     boolean inOpenRange(K key) {
3091     return m.inOpenRange(key, least, fence);
3092     }
3093    
3094     ConcurrentSkipListMap.Node<K,V> firstNode() {
3095     return m.findCeiling(least);
3096     }
3097    
3098     ConcurrentSkipListMap.Node<K,V> lastNode() {
3099     return m.findLower(fence);
3100     }
3101    
3102     boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
3103     return (n != null &&
3104     (fence == null ||
3105     n.key == null || // pass by markers and headers
3106     m.compare(fence, n.key) > 0));
3107     }
3108    
3109     void checkKey(K key) throws IllegalArgumentException {
3110     if (!inHalfOpenRange(key))
3111     throw new IllegalArgumentException("key out of range");
3112     }
3113    
3114     /**
3115     * Returns underlying map. Needed by ConcurrentSkipListSet
3116     * @return the backing map
3117     */
3118     ConcurrentSkipListMap<K,V> getMap() {
3119     return m;
3120     }
3121    
3122     /**
3123     * Returns least key. Needed by ConcurrentSkipListSet
3124     * @return least key or <tt>null</tt> if from start
3125     */
3126     K getLeast() {
3127     return least;
3128     }
3129    
3130     /**
3131     * Returns fence key. Needed by ConcurrentSkipListSet
3132     * @return fence key or <tt>null</tt> of to end
3133     */
3134     K getFence() {
3135     return fence;
3136     }
3137    
3138    
3139     /* ---------------- Map API methods -------------- */
3140    
3141     public boolean containsKey(Object key) {
3142     K k = (K)key;
3143     return inHalfOpenRange(k) && m.containsKey(k);
3144     }
3145    
3146     public V get(Object key) {
3147     K k = (K)key;
3148     return ((!inHalfOpenRange(k)) ? null : m.get(k));
3149     }
3150    
3151     public V put(K key, V value) {
3152     checkKey(key);
3153     return m.put(key, value);
3154     }
3155    
3156     public V remove(Object key) {
3157     K k = (K)key;
3158     return (!inHalfOpenRange(k))? null : m.remove(k);
3159     }
3160    
3161     public int size() {
3162     long count = 0;
3163     for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3164     isBeforeEnd(n);
3165     n = n.next) {
3166     if (n.getValidValue() != null)
3167     ++count;
3168     }
3169     return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count;
3170     }
3171    
3172     public boolean isEmpty() {
3173     return !isBeforeEnd(firstNode());
3174     }
3175    
3176     public boolean containsValue(Object value) {
3177     if (value == null)
3178     throw new NullPointerException();
3179     for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3180     isBeforeEnd(n);
3181     n = n.next) {
3182     V v = n.getValidValue();
3183     if (v != null && value.equals(v))
3184     return true;
3185     }
3186     return false;
3187     }
3188    
3189     public void clear() {
3190     for (ConcurrentSkipListMap.Node<K,V> n = firstNode();
3191     isBeforeEnd(n);
3192     n = n.next) {
3193     if (n.getValidValue() != null)
3194     m.remove(n.key);
3195     }
3196     }
3197    
3198     /* ---------------- ConcurrentMap API methods -------------- */
3199    
3200     public V putIfAbsent(K key, V value) {
3201     checkKey(key);
3202     return m.putIfAbsent(key, value);
3203     }
3204    
3205     public boolean remove(Object key, Object value) {
3206     K k = (K)key;
3207     return inHalfOpenRange(k) && m.remove(k, value);
3208     }
3209    
3210     public boolean replace(K key, V oldValue, V newValue) {
3211     checkKey(key);
3212     return m.replace(key, oldValue, newValue);
3213     }
3214    
3215     public V replace(K key, V value) {
3216     checkKey(key);
3217     return m.replace(key, value);
3218     }
3219    
3220     /* ---------------- SortedMap API methods -------------- */
3221    
3222     public Comparator<? super K> comparator() {
3223     return m.comparator();
3224     }
3225    
3226     public K firstKey() {
3227     ConcurrentSkipListMap.Node<K,V> n = firstNode();
3228     if (isBeforeEnd(n))
3229     return n.key;
3230     else
3231     throw new NoSuchElementException();
3232     }
3233    
3234     public K lastKey() {
3235     ConcurrentSkipListMap.Node<K,V> n = lastNode();
3236     if (n != null) {
3237     K last = n.key;
3238     if (inHalfOpenRange(last))
3239     return last;
3240     }
3241     throw new NoSuchElementException();
3242     }
3243    
3244     public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
3245     if (fromKey == null || toKey == null)
3246     throw new NullPointerException();
3247     if (!inOpenRange(fromKey) || !inOpenRange(toKey))
3248     throw new IllegalArgumentException("key out of range");
3249     return new ConcurrentSkipListSubMap(m, fromKey, toKey);
3250     }
3251    
3252     public ConcurrentNavigableMap<K,V> headMap(K toKey) {
3253     if (toKey == null)
3254     throw new NullPointerException();
3255     if (!inOpenRange(toKey))
3256     throw new IllegalArgumentException("key out of range");
3257     return new ConcurrentSkipListSubMap(m, least, toKey);
3258     }
3259    
3260     public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
3261     if (fromKey == null)
3262     throw new NullPointerException();
3263     if (!inOpenRange(fromKey))
3264     throw new IllegalArgumentException("key out of range");
3265     return new ConcurrentSkipListSubMap(m, fromKey, fence);
3266     }
3267    
3268     /* ---------------- Relational methods -------------- */
3269    
3270     public Map.Entry<K,V> ceilingEntry(K key) {
3271 dl 1.2 return (Map.Entry<K,V>)
3272 dl 1.1 m.getNear(key, m.GT|m.EQ, least, fence, false);
3273     }
3274    
3275     public K ceilingKey(K key) {
3276     return (K)
3277     m.getNear(key, m.GT|m.EQ, least, fence, true);
3278     }
3279    
3280     public Map.Entry<K,V> lowerEntry(K key) {
3281 dl 1.2 return (Map.Entry<K,V>)
3282 dl 1.1 m.getNear(key, m.LT, least, fence, false);
3283     }
3284    
3285     public K lowerKey(K key) {
3286     return (K)
3287     m.getNear(key, m.LT, least, fence, true);
3288     }
3289    
3290     public Map.Entry<K,V> floorEntry(K key) {
3291 dl 1.2 return (Map.Entry<K,V>)
3292 dl 1.1 m.getNear(key, m.LT|m.EQ, least, fence, false);
3293     }
3294    
3295     public K floorKey(K key) {
3296     return (K)
3297     m.getNear(key, m.LT|m.EQ, least, fence, true);
3298     }
3299    
3300    
3301     public Map.Entry<K,V> higherEntry(K key) {
3302 dl 1.2 return (Map.Entry<K,V>)
3303 dl 1.1 m.getNear(key, m.GT, least, fence, false);
3304     }
3305    
3306     public K higherKey(K key) {
3307     return (K)
3308     m.getNear(key, m.GT, least, fence, true);
3309     }
3310    
3311     public Map.Entry<K,V> firstEntry() {
3312     for (;;) {
3313     ConcurrentSkipListMap.Node<K,V> n = firstNode();
3314     if (!isBeforeEnd(n))
3315     return null;
3316     Map.Entry<K,V> e = n.createSnapshot();
3317     if (e != null)
3318     return e;
3319     }
3320     }
3321    
3322     public Map.Entry<K,V> lastEntry() {
3323     for (;;) {
3324     ConcurrentSkipListMap.Node<K,V> n = lastNode();
3325     if (n == null || !inHalfOpenRange(n.key))
3326     return null;
3327     Map.Entry<K,V> e = n.createSnapshot();
3328     if (e != null)
3329     return e;
3330     }
3331     }
3332    
3333     public Map.Entry<K,V> pollFirstEntry() {
3334 dl 1.2 return (Map.Entry<K,V>)
3335 dl 1.1 m.removeFirstEntryOfSubrange(least, fence, false);
3336     }
3337    
3338     public Map.Entry<K,V> pollLastEntry() {
3339 dl 1.2 return (Map.Entry<K,V>)
3340 dl 1.1 m.removeLastEntryOfSubrange(least, fence, false);
3341     }
3342    
3343     /* ---------------- Submap Views -------------- */
3344    
3345     public Set<K> keySet() {
3346     Set<K> ks = keySetView;
3347     return (ks != null) ? ks : (keySetView = new KeySetView());
3348     }
3349    
3350     class KeySetView extends AbstractSet<K> {
3351     public Iterator<K> iterator() {
3352     return m.subMapKeyIterator(least, fence);
3353     }
3354     public int size() {
3355     return ConcurrentSkipListSubMap.this.size();
3356     }
3357     public boolean isEmpty() {
3358     return ConcurrentSkipListSubMap.this.isEmpty();
3359     }
3360     public boolean contains(Object k) {
3361     return ConcurrentSkipListSubMap.this.containsKey(k);
3362     }
3363     public Object[] toArray() {
3364     Collection<K> c = new ArrayList<K>();
3365     for (Iterator<K> i = iterator(); i.hasNext(); )
3366     c.add(i.next());
3367     return c.toArray();
3368     }
3369     public <T> T[] toArray(T[] a) {
3370     Collection<K> c = new ArrayList<K>();
3371     for (Iterator<K> i = iterator(); i.hasNext(); )
3372     c.add(i.next());
3373     return c.toArray(a);
3374     }
3375     }
3376    
3377     public Set<K> descendingKeySet() {
3378     Set<K> ks = descendingKeySetView;
3379     return (ks != null) ? ks : (descendingKeySetView = new DescendingKeySetView());
3380     }
3381    
3382     class DescendingKeySetView extends KeySetView {
3383     public Iterator<K> iterator() {
3384     return m.descendingSubMapKeyIterator(least, fence);
3385     }
3386     }
3387    
3388     public Collection<V> values() {
3389     Collection<V> vs = valuesView;
3390     return (vs != null) ? vs : (valuesView = new ValuesView());
3391     }
3392    
3393     class ValuesView extends AbstractCollection<V> {
3394     public Iterator<V> iterator() {
3395     return m.subMapValueIterator(least, fence);
3396     }
3397     public int size() {
3398     return ConcurrentSkipListSubMap.this.size();
3399     }
3400     public boolean isEmpty() {
3401     return ConcurrentSkipListSubMap.this.isEmpty();
3402     }
3403     public boolean contains(Object v) {
3404     return ConcurrentSkipListSubMap.this.containsValue(v);
3405     }
3406     public Object[] toArray() {
3407     Collection<V> c = new ArrayList<V>();
3408     for (Iterator<V> i = iterator(); i.hasNext(); )
3409     c.add(i.next());
3410     return c.toArray();
3411     }
3412     public <T> T[] toArray(T[] a) {
3413     Collection<V> c = new ArrayList<V>();
3414     for (Iterator<V> i = iterator(); i.hasNext(); )
3415     c.add(i.next());
3416     return c.toArray(a);
3417     }
3418     }
3419    
3420     public Set<Map.Entry<K,V>> entrySet() {
3421     Set<Map.Entry<K,V>> es = entrySetView;
3422     return (es != null) ? es : (entrySetView = new EntrySetView());
3423     }
3424    
3425     class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
3426     public Iterator<Map.Entry<K,V>> iterator() {
3427     return m.subMapEntryIterator(least, fence);
3428     }
3429     public int size() {
3430     return ConcurrentSkipListSubMap.this.size();
3431     }
3432     public boolean isEmpty() {
3433     return ConcurrentSkipListSubMap.this.isEmpty();
3434     }
3435     public boolean contains(Object o) {
3436     if (!(o instanceof Map.Entry))
3437     return false;
3438     Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3439     K key = e.getKey();
3440     if (!inHalfOpenRange(key))
3441     return false;
3442     V v = m.get(key);
3443     return v != null && v.equals(e.getValue());
3444     }
3445     public boolean remove(Object o) {
3446     if (!(o instanceof Map.Entry))
3447     return false;
3448     Map.Entry<K,V> e = (Map.Entry<K,V>) o;
3449     K key = e.getKey();
3450     if (!inHalfOpenRange(key))
3451     return false;
3452     return m.remove(key, e.getValue());
3453     }
3454     public Object[] toArray() {
3455     Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3456     for (Map.Entry e : this)
3457 dl 1.2 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3458 dl 1.1 return c.toArray();
3459     }
3460     public <T> T[] toArray(T[] a) {
3461     Collection<Map.Entry<K,V>> c = new ArrayList<Map.Entry<K,V>>();
3462     for (Map.Entry e : this)
3463 dl 1.2 c.add(new AbstractMap.SimpleEntry(e.getKey(), e.getValue()));
3464 dl 1.1 return c.toArray(a);
3465     }
3466     }
3467    
3468     public Set<Map.Entry<K,V>> descendingEntrySet() {
3469     Set<Map.Entry<K,V>> es = descendingEntrySetView;
3470     return (es != null) ? es : (descendingEntrySetView = new DescendingEntrySetView());
3471     }
3472    
3473     class DescendingEntrySetView extends EntrySetView {
3474     public Iterator<Map.Entry<K,V>> iterator() {
3475     return m.descendingSubMapEntryIterator(least, fence);
3476     }
3477     }
3478     }
3479     }