ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.45
Committed: Fri Feb 10 12:17:56 2006 UTC (18 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.44: +59 -0 lines
Log Message:
remove(null, null) should check key argument for null first

File Contents

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