ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.51
Committed: Tue May 2 19:55:15 2006 UTC (18 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.50: +15 -34 lines
Log Message:
6415641: (coll) Getting NavigableMap/NavigableSet right

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 jsr166 1.51 * multiple threads. Iterators are <i>weakly consistent</i>, returning
24 dl 1.1 * 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 jsr166 1.51 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
56 jsr166 1.21 * 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 dl 1.46 private transient ConcurrentNavigableMap<K,V> descendingMap;
332 dl 1.1
333     /**
334 jsr166 1.13 * Initializes or resets state. Needed by constructors, clone,
335 dl 1.1 * clear, readObject. and ConcurrentSkipListSet.clone.
336     * (Note that comparator must be separately initialized.)
337     */
338     final void initialize() {
339     keySet = null;
340 dl 1.9 entrySet = null;
341 dl 1.1 values = null;
342 dl 1.46 descendingMap = null;
343 dl 1.40 randomSeed = seedGenerator.nextInt() | 0x0100; // ensure nonzero
344 dl 1.1 head = new HeadIndex<K,V>(new Node<K,V>(null, BASE_HEADER, null),
345     null, null, 1);
346     }
347    
348     /** Updater for casHead */
349 dl 1.9 private static final
350     AtomicReferenceFieldUpdater<ConcurrentSkipListMap, HeadIndex>
351 dl 1.1 headUpdater = AtomicReferenceFieldUpdater.newUpdater
352     (ConcurrentSkipListMap.class, HeadIndex.class, "head");
353    
354     /**
355     * compareAndSet head node
356     */
357     private boolean casHead(HeadIndex<K,V> cmp, HeadIndex<K,V> val) {
358     return headUpdater.compareAndSet(this, cmp, val);
359     }
360    
361     /* ---------------- Nodes -------------- */
362    
363     /**
364     * Nodes hold keys and values, and are singly linked in sorted
365     * order, possibly with some intervening marker nodes. The list is
366     * headed by a dummy node accessible as head.node. The value field
367     * is declared only as Object because it takes special non-V
368     * values for marker and header nodes.
369     */
370     static final class Node<K,V> {
371     final K key;
372     volatile Object value;
373     volatile Node<K,V> next;
374    
375     /**
376     * Creates a new regular node.
377     */
378     Node(K key, Object value, Node<K,V> next) {
379     this.key = key;
380     this.value = value;
381     this.next = next;
382     }
383    
384     /**
385     * Creates a new marker node. A marker is distinguished by
386     * having its value field point to itself. Marker nodes also
387     * have null keys, a fact that is exploited in a few places,
388     * but this doesn't distinguish markers from the base-level
389     * header node (head.node), which also has a null key.
390     */
391     Node(Node<K,V> next) {
392     this.key = null;
393     this.value = this;
394     this.next = next;
395     }
396    
397     /** Updater for casNext */
398 dl 1.9 static final AtomicReferenceFieldUpdater<Node, Node>
399 dl 1.1 nextUpdater = AtomicReferenceFieldUpdater.newUpdater
400     (Node.class, Node.class, "next");
401    
402     /** Updater for casValue */
403 dl 1.9 static final AtomicReferenceFieldUpdater<Node, Object>
404 dl 1.1 valueUpdater = AtomicReferenceFieldUpdater.newUpdater
405     (Node.class, Object.class, "value");
406    
407     /**
408     * compareAndSet value field
409     */
410     boolean casValue(Object cmp, Object val) {
411     return valueUpdater.compareAndSet(this, cmp, val);
412     }
413    
414     /**
415     * compareAndSet next field
416     */
417     boolean casNext(Node<K,V> cmp, Node<K,V> val) {
418     return nextUpdater.compareAndSet(this, cmp, val);
419     }
420    
421     /**
422 jsr166 1.10 * Returns true if this node is a marker. This method isn't
423     * actually called in any current code checking for markers
424 dl 1.1 * because callers will have already read value field and need
425     * to use that read (not another done here) and so directly
426     * test if value points to node.
427     * @param n a possibly null reference to a node
428     * @return true if this node is a marker node
429     */
430     boolean isMarker() {
431     return value == this;
432     }
433    
434     /**
435 jsr166 1.10 * Returns true if this node is the header of base-level list.
436 dl 1.1 * @return true if this node is header node
437     */
438     boolean isBaseHeader() {
439     return value == BASE_HEADER;
440     }
441    
442     /**
443     * Tries to append a deletion marker to this node.
444     * @param f the assumed current successor of this node
445     * @return true if successful
446     */
447     boolean appendMarker(Node<K,V> f) {
448     return casNext(f, new Node<K,V>(f));
449     }
450    
451     /**
452     * Helps out a deletion by appending marker or unlinking from
453     * predecessor. This is called during traversals when value
454     * field seen to be null.
455     * @param b predecessor
456     * @param f successor
457     */
458     void helpDelete(Node<K,V> b, Node<K,V> f) {
459     /*
460     * Rechecking links and then doing only one of the
461     * help-out stages per call tends to minimize CAS
462     * interference among helping threads.
463     */
464     if (f == next && this == b.next) {
465     if (f == null || f.value != f) // not already marked
466     appendMarker(f);
467     else
468     b.casNext(this, f.next);
469     }
470     }
471    
472     /**
473 jsr166 1.11 * Returns value if this node contains a valid key-value pair,
474 dl 1.9 * else null.
475 dl 1.1 * @return this node's value if it isn't a marker or header or
476     * is deleted, else null.
477     */
478     V getValidValue() {
479     Object v = value;
480     if (v == this || v == BASE_HEADER)
481     return null;
482     return (V)v;
483     }
484    
485     /**
486 jsr166 1.10 * Creates and returns a new SimpleImmutableEntry holding current
487     * mapping if this node holds a valid value, else null.
488 dl 1.1 * @return new entry or null
489     */
490 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
491 dl 1.1 V v = getValidValue();
492     if (v == null)
493     return null;
494 dl 1.24 return new AbstractMap.SimpleImmutableEntry<K,V>(key, v);
495 dl 1.1 }
496     }
497    
498     /* ---------------- Indexing -------------- */
499    
500     /**
501 dl 1.40 * Index nodes represent the levels of the skip list. Note that
502     * even though both Nodes and Indexes have forward-pointing
503     * fields, they have different types and are handled in different
504     * ways, that can't nicely be captured by placing field in a
505     * shared abstract class.
506 dl 1.1 */
507     static class Index<K,V> {
508     final Node<K,V> node;
509     final Index<K,V> down;
510     volatile Index<K,V> right;
511    
512     /**
513 jsr166 1.10 * Creates index node with given values.
514 dl 1.9 */
515 dl 1.1 Index(Node<K,V> node, Index<K,V> down, Index<K,V> right) {
516     this.node = node;
517     this.down = down;
518     this.right = right;
519     }
520    
521     /** Updater for casRight */
522 dl 1.9 static final AtomicReferenceFieldUpdater<Index, Index>
523 dl 1.1 rightUpdater = AtomicReferenceFieldUpdater.newUpdater
524     (Index.class, Index.class, "right");
525    
526     /**
527     * compareAndSet right field
528     */
529     final boolean casRight(Index<K,V> cmp, Index<K,V> val) {
530     return rightUpdater.compareAndSet(this, cmp, val);
531     }
532    
533     /**
534     * Returns true if the node this indexes has been deleted.
535     * @return true if indexed node is known to be deleted
536     */
537     final boolean indexesDeletedNode() {
538     return node.value == null;
539     }
540    
541     /**
542     * Tries to CAS newSucc as successor. To minimize races with
543     * unlink that may lose this index node, if the node being
544     * indexed is known to be deleted, it doesn't try to link in.
545     * @param succ the expected current successor
546     * @param newSucc the new successor
547     * @return true if successful
548     */
549     final boolean link(Index<K,V> succ, Index<K,V> newSucc) {
550     Node<K,V> n = node;
551 dl 1.9 newSucc.right = succ;
552 dl 1.1 return n.value != null && casRight(succ, newSucc);
553     }
554    
555     /**
556     * Tries to CAS right field to skip over apparent successor
557     * succ. Fails (forcing a retraversal by caller) if this node
558     * is known to be deleted.
559     * @param succ the expected current successor
560     * @return true if successful
561     */
562     final boolean unlink(Index<K,V> succ) {
563     return !indexesDeletedNode() && casRight(succ, succ.right);
564     }
565     }
566    
567     /* ---------------- Head nodes -------------- */
568    
569     /**
570     * Nodes heading each level keep track of their level.
571     */
572     static final class HeadIndex<K,V> extends Index<K,V> {
573     final int level;
574     HeadIndex(Node<K,V> node, Index<K,V> down, Index<K,V> right, int level) {
575     super(node, down, right);
576     this.level = level;
577     }
578 dl 1.9 }
579 dl 1.1
580     /* ---------------- Comparison utilities -------------- */
581    
582     /**
583     * Represents a key with a comparator as a Comparable.
584     *
585 jsr166 1.22 * Because most sorted collections seem to use natural ordering on
586 dl 1.1 * Comparables (Strings, Integers, etc), most internal methods are
587     * geared to use them. This is generally faster than checking
588     * per-comparison whether to use comparator or comparable because
589     * it doesn't require a (Comparable) cast for each comparison.
590     * (Optimizers can only sometimes remove such redundant checks
591     * themselves.) When Comparators are used,
592     * ComparableUsingComparators are created so that they act in the
593     * same way as natural orderings. This penalizes use of
594     * Comparators vs Comparables, which seems like the right
595     * tradeoff.
596     */
597     static final class ComparableUsingComparator<K> implements Comparable<K> {
598     final K actualKey;
599     final Comparator<? super K> cmp;
600     ComparableUsingComparator(K key, Comparator<? super K> cmp) {
601     this.actualKey = key;
602     this.cmp = cmp;
603     }
604     public int compareTo(K k2) {
605     return cmp.compare(actualKey, k2);
606     }
607     }
608    
609     /**
610     * If using comparator, return a ComparableUsingComparator, else
611 jsr166 1.50 * cast key as Comparable, which may cause ClassCastException,
612 dl 1.1 * which is propagated back to caller.
613     */
614 dl 1.9 private Comparable<? super K> comparable(Object key) throws ClassCastException {
615     if (key == null)
616 dl 1.1 throw new NullPointerException();
617 dl 1.24 if (comparator != null)
618     return new ComparableUsingComparator<K>((K)key, comparator);
619     else
620     return (Comparable<? super K>)key;
621 dl 1.1 }
622    
623     /**
624 jsr166 1.10 * Compares using comparator or natural ordering. Used when the
625 dl 1.1 * ComparableUsingComparator approach doesn't apply.
626     */
627     int compare(K k1, K k2) throws ClassCastException {
628     Comparator<? super K> cmp = comparator;
629     if (cmp != null)
630     return cmp.compare(k1, k2);
631     else
632 jsr166 1.18 return ((Comparable<? super K>)k1).compareTo(k2);
633 dl 1.1 }
634    
635     /**
636 jsr166 1.10 * Returns true if given key greater than or equal to least and
637 dl 1.1 * strictly less than fence, bypassing either test if least or
638 dl 1.5 * fence are null. Needed mainly in submap operations.
639 dl 1.1 */
640     boolean inHalfOpenRange(K key, K least, K fence) {
641 dl 1.9 if (key == null)
642 dl 1.1 throw new NullPointerException();
643     return ((least == null || compare(key, least) >= 0) &&
644     (fence == null || compare(key, fence) < 0));
645     }
646    
647     /**
648 jsr166 1.10 * Returns true if given key greater than or equal to least and less
649 dl 1.1 * or equal to fence. Needed mainly in submap operations.
650     */
651     boolean inOpenRange(K key, K least, K fence) {
652 dl 1.9 if (key == null)
653 dl 1.1 throw new NullPointerException();
654     return ((least == null || compare(key, least) >= 0) &&
655     (fence == null || compare(key, fence) <= 0));
656     }
657    
658     /* ---------------- Traversal -------------- */
659    
660     /**
661 jsr166 1.10 * Returns a base-level node with key strictly less than given key,
662 dl 1.1 * or the base-level header if there is no such node. Also
663     * unlinks indexes to deleted nodes found along the way. Callers
664     * rely on this side-effect of clearing indices to deleted nodes.
665     * @param key the key
666 dl 1.9 * @return a predecessor of key
667 dl 1.1 */
668 dl 1.9 private Node<K,V> findPredecessor(Comparable<? super K> key) {
669 jsr166 1.41 if (key == null)
670 dl 1.40 throw new NullPointerException(); // don't postpone errors
671 dl 1.1 for (;;) {
672     Index<K,V> q = head;
673 dl 1.40 Index<K,V> r = q.right;
674 dl 1.1 for (;;) {
675 dl 1.40 if (r != null) {
676     Node<K,V> n = r.node;
677     K k = n.key;
678     if (n.value == null) {
679     if (!q.unlink(r))
680     break; // restart
681     r = q.right; // reread r
682     continue;
683 dl 1.1 }
684 dl 1.40 if (key.compareTo(k) > 0) {
685 dl 1.1 q = r;
686 dl 1.40 r = r.right;
687 dl 1.1 continue;
688     }
689     }
690 dl 1.40 Index<K,V> d = q.down;
691     if (d != null) {
692 dl 1.1 q = d;
693 dl 1.40 r = d.right;
694     } else
695 dl 1.1 return q.node;
696     }
697     }
698     }
699    
700     /**
701 jsr166 1.10 * Returns node holding key or null if no such, clearing out any
702 dl 1.1 * deleted nodes seen along the way. Repeatedly traverses at
703     * base-level looking for key starting at predecessor returned
704     * from findPredecessor, processing base-level deletions as
705     * encountered. Some callers rely on this side-effect of clearing
706     * deleted nodes.
707     *
708     * Restarts occur, at traversal step centered on node n, if:
709     *
710     * (1) After reading n's next field, n is no longer assumed
711     * predecessor b's current successor, which means that
712     * we don't have a consistent 3-node snapshot and so cannot
713     * unlink any subsequent deleted nodes encountered.
714     *
715     * (2) n's value field is null, indicating n is deleted, in
716     * which case we help out an ongoing structural deletion
717     * before retrying. Even though there are cases where such
718     * unlinking doesn't require restart, they aren't sorted out
719     * here because doing so would not usually outweigh cost of
720     * restarting.
721     *
722 dl 1.9 * (3) n is a marker or n's predecessor's value field is null,
723 dl 1.1 * indicating (among other possibilities) that
724     * findPredecessor returned a deleted node. We can't unlink
725     * the node because we don't know its predecessor, so rely
726     * on another call to findPredecessor to notice and return
727     * some earlier predecessor, which it will do. This check is
728     * only strictly needed at beginning of loop, (and the
729     * b.value check isn't strictly needed at all) but is done
730     * each iteration to help avoid contention with other
731     * threads by callers that will fail to be able to change
732     * links, and so will retry anyway.
733     *
734     * The traversal loops in doPut, doRemove, and findNear all
735     * include the same three kinds of checks. And specialized
736 dl 1.31 * versions appear in findFirst, and findLast and their
737     * variants. They can't easily share code because each uses the
738 dl 1.1 * reads of fields held in locals occurring in the orders they
739     * were performed.
740 dl 1.9 *
741 dl 1.1 * @param key the key
742 jsr166 1.22 * @return node holding key, or null if no such
743 dl 1.1 */
744 dl 1.9 private Node<K,V> findNode(Comparable<? super K> key) {
745 dl 1.1 for (;;) {
746     Node<K,V> b = findPredecessor(key);
747     Node<K,V> n = b.next;
748     for (;;) {
749 dl 1.9 if (n == null)
750 dl 1.1 return null;
751     Node<K,V> f = n.next;
752     if (n != b.next) // inconsistent read
753     break;
754     Object v = n.value;
755     if (v == null) { // n is deleted
756     n.helpDelete(b, f);
757     break;
758     }
759     if (v == n || b.value == null) // b is deleted
760     break;
761     int c = key.compareTo(n.key);
762 dl 1.40 if (c == 0)
763     return n;
764 dl 1.1 if (c < 0)
765     return null;
766     b = n;
767     n = f;
768     }
769     }
770     }
771    
772 dl 1.9 /**
773 dl 1.1 * Specialized variant of findNode to perform Map.get. Does a weak
774     * traversal, not bothering to fix any deleted index nodes,
775     * returning early if it happens to see key in index, and passing
776     * over any deleted base nodes, falling back to getUsingFindNode
777     * only if it would otherwise return value from an ongoing
778     * deletion. Also uses "bound" to eliminate need for some
779     * comparisons (see Pugh Cookbook). Also folds uses of null checks
780     * and node-skipping because markers have null keys.
781     * @param okey the key
782     * @return the value, or null if absent
783     */
784     private V doGet(Object okey) {
785 dl 1.9 Comparable<? super K> key = comparable(okey);
786 dl 1.40 Node<K,V> bound = null;
787 dl 1.1 Index<K,V> q = head;
788 dl 1.40 Index<K,V> r = q.right;
789     Node<K,V> n;
790     K k;
791     int c;
792     for (;;) {
793     Index<K,V> d;
794     // Traverse rights
795     if (r != null && (n = r.node) != bound && (k = n.key) != null) {
796     if ((c = key.compareTo(k)) > 0) {
797 dl 1.1 q = r;
798 dl 1.40 r = r.right;
799 dl 1.1 continue;
800 dl 1.40 } else if (c == 0) {
801     Object v = n.value;
802 dl 1.1 return (v != null)? (V)v : getUsingFindNode(key);
803 dl 1.40 } else
804     bound = n;
805 dl 1.1 }
806 dl 1.40
807     // Traverse down
808     if ((d = q.down) != null) {
809 dl 1.1 q = d;
810 dl 1.40 r = d.right;
811     } else
812     break;
813     }
814    
815     // Traverse nexts
816     for (n = q.node.next; n != null; n = n.next) {
817     if ((k = n.key) != null) {
818     if ((c = key.compareTo(k)) == 0) {
819     Object v = n.value;
820     return (v != null)? (V)v : getUsingFindNode(key);
821     } else if (c < 0)
822     break;
823 dl 1.1 }
824     }
825 dl 1.40 return null;
826 dl 1.1 }
827    
828     /**
829 jsr166 1.10 * Performs map.get via findNode. Used as a backup if doGet
830 dl 1.1 * encounters an in-progress deletion.
831     * @param key the key
832     * @return the value, or null if absent
833     */
834 dl 1.9 private V getUsingFindNode(Comparable<? super K> key) {
835 dl 1.1 /*
836     * Loop needed here and elsewhere in case value field goes
837     * null just as it is about to be returned, in which case we
838     * lost a race with a deletion, so must retry.
839     */
840     for (;;) {
841     Node<K,V> n = findNode(key);
842     if (n == null)
843     return null;
844     Object v = n.value;
845     if (v != null)
846     return (V)v;
847     }
848     }
849    
850     /* ---------------- Insertion -------------- */
851    
852     /**
853     * Main insertion method. Adds element if not present, or
854     * replaces value if present and onlyIfAbsent is false.
855 dl 1.9 * @param kkey the key
856 dl 1.1 * @param value the value that must be associated with key
857     * @param onlyIfAbsent if should not insert if already present
858     * @return the old value, or null if newly inserted
859     */
860     private V doPut(K kkey, V value, boolean onlyIfAbsent) {
861 dl 1.9 Comparable<? super K> key = comparable(kkey);
862 dl 1.1 for (;;) {
863     Node<K,V> b = findPredecessor(key);
864     Node<K,V> n = b.next;
865     for (;;) {
866     if (n != null) {
867     Node<K,V> f = n.next;
868     if (n != b.next) // inconsistent read
869     break;;
870     Object v = n.value;
871     if (v == null) { // n is deleted
872     n.helpDelete(b, f);
873     break;
874     }
875     if (v == n || b.value == null) // b is deleted
876     break;
877     int c = key.compareTo(n.key);
878     if (c > 0) {
879     b = n;
880     n = f;
881     continue;
882     }
883     if (c == 0) {
884     if (onlyIfAbsent || n.casValue(v, value))
885     return (V)v;
886     else
887     break; // restart if lost race to replace value
888     }
889     // else c < 0; fall through
890     }
891 dl 1.9
892 dl 1.1 Node<K,V> z = new Node<K,V>(kkey, value, n);
893 dl 1.9 if (!b.casNext(n, z))
894 dl 1.1 break; // restart if lost race to append to b
895 dl 1.9 int level = randomLevel();
896     if (level > 0)
897 dl 1.1 insertIndex(z, level);
898     return null;
899     }
900     }
901     }
902    
903     /**
904 jsr166 1.10 * Returns a random level for inserting a new node.
905 dl 1.35 * Hardwired to k=1, p=0.5, max 31 (see above and
906 dl 1.34 * Pugh's "Skip List Cookbook", sec 3.4).
907 dl 1.1 *
908 dl 1.33 * This uses the simplest of the generators described in George
909     * Marsaglia's "Xorshift RNGs" paper. This is not a high-quality
910 dl 1.40 * generator but is acceptable here.
911 dl 1.1 */
912     private int randomLevel() {
913 dl 1.40 int x = randomSeed;
914     x ^= x << 13;
915 dl 1.33 x ^= x >>> 17;
916 dl 1.40 randomSeed = x ^= x << 5;
917     if ((x & 0x8001) != 0) // test highest and lowest bits
918     return 0;
919     int level = 1;
920     while (((x >>>= 1) & 1) != 0) ++level;
921 dl 1.1 return level;
922     }
923    
924     /**
925 jsr166 1.11 * Creates and adds index nodes for the given node.
926 dl 1.1 * @param z the node
927     * @param level the level of the index
928     */
929     private void insertIndex(Node<K,V> z, int level) {
930     HeadIndex<K,V> h = head;
931     int max = h.level;
932    
933     if (level <= max) {
934     Index<K,V> idx = null;
935     for (int i = 1; i <= level; ++i)
936     idx = new Index<K,V>(z, idx, null);
937     addIndex(idx, h, level);
938    
939     } else { // Add a new level
940     /*
941     * To reduce interference by other threads checking for
942     * empty levels in tryReduceLevel, new levels are added
943     * with initialized right pointers. Which in turn requires
944     * keeping levels in an array to access them while
945     * creating new head index nodes from the opposite
946     * direction.
947     */
948     level = max + 1;
949     Index<K,V>[] idxs = (Index<K,V>[])new Index[level+1];
950     Index<K,V> idx = null;
951 dl 1.9 for (int i = 1; i <= level; ++i)
952 dl 1.1 idxs[i] = idx = new Index<K,V>(z, idx, null);
953    
954     HeadIndex<K,V> oldh;
955     int k;
956     for (;;) {
957     oldh = head;
958     int oldLevel = oldh.level;
959     if (level <= oldLevel) { // lost race to add level
960     k = level;
961     break;
962     }
963     HeadIndex<K,V> newh = oldh;
964     Node<K,V> oldbase = oldh.node;
965 dl 1.9 for (int j = oldLevel+1; j <= level; ++j)
966 dl 1.1 newh = new HeadIndex<K,V>(oldbase, newh, idxs[j], j);
967     if (casHead(oldh, newh)) {
968     k = oldLevel;
969     break;
970     }
971     }
972     addIndex(idxs[k], oldh, k);
973     }
974     }
975    
976     /**
977 jsr166 1.10 * Adds given index nodes from given level down to 1.
978 dl 1.1 * @param idx the topmost index node being inserted
979     * @param h the value of head to use to insert. This must be
980     * snapshotted by callers to provide correct insertion level
981     * @param indexLevel the level of the index
982     */
983     private void addIndex(Index<K,V> idx, HeadIndex<K,V> h, int indexLevel) {
984     // Track next level to insert in case of retries
985     int insertionLevel = indexLevel;
986 dl 1.40 Comparable<? super K> key = comparable(idx.node.key);
987     if (key == null) throw new NullPointerException();
988 dl 1.1
989     // Similar to findPredecessor, but adding index nodes along
990     // path to key.
991     for (;;) {
992 dl 1.40 int j = h.level;
993 dl 1.1 Index<K,V> q = h;
994 dl 1.40 Index<K,V> r = q.right;
995 dl 1.1 Index<K,V> t = idx;
996     for (;;) {
997     if (r != null) {
998 dl 1.40 Node<K,V> n = r.node;
999 dl 1.1 // compare before deletion check avoids needing recheck
1000 dl 1.40 int c = key.compareTo(n.key);
1001     if (n.value == null) {
1002     if (!q.unlink(r))
1003 dl 1.9 break;
1004 dl 1.40 r = q.right;
1005     continue;
1006 dl 1.1 }
1007     if (c > 0) {
1008     q = r;
1009 dl 1.40 r = r.right;
1010 dl 1.1 continue;
1011     }
1012     }
1013    
1014     if (j == insertionLevel) {
1015     // Don't insert index if node already deleted
1016     if (t.indexesDeletedNode()) {
1017     findNode(key); // cleans up
1018     return;
1019     }
1020 dl 1.9 if (!q.link(r, t))
1021 dl 1.1 break; // restart
1022     if (--insertionLevel == 0) {
1023     // need final deletion check before return
1024 dl 1.9 if (t.indexesDeletedNode())
1025     findNode(key);
1026 dl 1.1 return;
1027     }
1028     }
1029    
1030 dl 1.40 if (--j >= insertionLevel && j < indexLevel)
1031 dl 1.1 t = t.down;
1032     q = q.down;
1033 dl 1.40 r = q.right;
1034 dl 1.1 }
1035     }
1036     }
1037    
1038     /* ---------------- Deletion -------------- */
1039    
1040     /**
1041     * Main deletion method. Locates node, nulls value, appends a
1042     * deletion marker, unlinks predecessor, removes associated index
1043     * nodes, and possibly reduces head index level.
1044     *
1045     * Index nodes are cleared out simply by calling findPredecessor.
1046     * which unlinks indexes to deleted nodes found along path to key,
1047     * which will include the indexes to this node. This is done
1048     * unconditionally. We can't check beforehand whether there are
1049     * index nodes because it might be the case that some or all
1050     * indexes hadn't been inserted yet for this node during initial
1051     * search for it, and we'd like to ensure lack of garbage
1052 dl 1.9 * retention, so must call to be sure.
1053 dl 1.1 *
1054     * @param okey the key
1055     * @param value if non-null, the value that must be
1056     * associated with key
1057     * @return the node, or null if not found
1058     */
1059 dl 1.46 final V doRemove(Object okey, Object value) {
1060 dl 1.9 Comparable<? super K> key = comparable(okey);
1061     for (;;) {
1062 dl 1.1 Node<K,V> b = findPredecessor(key);
1063     Node<K,V> n = b.next;
1064     for (;;) {
1065 dl 1.9 if (n == null)
1066 dl 1.1 return null;
1067     Node<K,V> f = n.next;
1068     if (n != b.next) // inconsistent read
1069     break;
1070     Object v = n.value;
1071     if (v == null) { // n is deleted
1072     n.helpDelete(b, f);
1073     break;
1074     }
1075     if (v == n || b.value == null) // b is deleted
1076     break;
1077     int c = key.compareTo(n.key);
1078     if (c < 0)
1079     return null;
1080     if (c > 0) {
1081     b = n;
1082     n = f;
1083     continue;
1084     }
1085 dl 1.9 if (value != null && !value.equals(v))
1086     return null;
1087     if (!n.casValue(v, null))
1088 dl 1.1 break;
1089 dl 1.9 if (!n.appendMarker(f) || !b.casNext(n, f))
1090 dl 1.1 findNode(key); // Retry via findNode
1091     else {
1092     findPredecessor(key); // Clean index
1093 dl 1.9 if (head.right == null)
1094 dl 1.1 tryReduceLevel();
1095     }
1096     return (V)v;
1097     }
1098     }
1099     }
1100    
1101     /**
1102     * Possibly reduce head level if it has no nodes. This method can
1103     * (rarely) make mistakes, in which case levels can disappear even
1104     * though they are about to contain index nodes. This impacts
1105     * performance, not correctness. To minimize mistakes as well as
1106     * to reduce hysteresis, the level is reduced by one only if the
1107     * topmost three levels look empty. Also, if the removed level
1108     * looks non-empty after CAS, we try to change it back quick
1109     * before anyone notices our mistake! (This trick works pretty
1110     * well because this method will practically never make mistakes
1111     * unless current thread stalls immediately before first CAS, in
1112     * which case it is very unlikely to stall again immediately
1113     * afterwards, so will recover.)
1114     *
1115     * We put up with all this rather than just let levels grow
1116     * because otherwise, even a small map that has undergone a large
1117     * number of insertions and removals will have a lot of levels,
1118     * slowing down access more than would an occasional unwanted
1119     * reduction.
1120     */
1121     private void tryReduceLevel() {
1122     HeadIndex<K,V> h = head;
1123     HeadIndex<K,V> d;
1124     HeadIndex<K,V> e;
1125     if (h.level > 3 &&
1126 dl 1.9 (d = (HeadIndex<K,V>)h.down) != null &&
1127     (e = (HeadIndex<K,V>)d.down) != null &&
1128     e.right == null &&
1129     d.right == null &&
1130 dl 1.1 h.right == null &&
1131     casHead(h, d) && // try to set
1132     h.right != null) // recheck
1133     casHead(d, h); // try to backout
1134     }
1135    
1136     /* ---------------- Finding and removing first element -------------- */
1137    
1138     /**
1139 jsr166 1.22 * Specialized variant of findNode to get first valid node.
1140 dl 1.1 * @return first node or null if empty
1141     */
1142     Node<K,V> findFirst() {
1143     for (;;) {
1144     Node<K,V> b = head.node;
1145     Node<K,V> n = b.next;
1146     if (n == null)
1147     return null;
1148 dl 1.9 if (n.value != null)
1149 dl 1.1 return n;
1150     n.helpDelete(b, n.next);
1151     }
1152     }
1153    
1154     /**
1155 dl 1.25 * Removes first entry; returns its snapshot.
1156 jsr166 1.28 * @return null if empty, else snapshot of first entry
1157 dl 1.1 */
1158 dl 1.25 Map.Entry<K,V> doRemoveFirstEntry() {
1159 dl 1.9 for (;;) {
1160 dl 1.1 Node<K,V> b = head.node;
1161     Node<K,V> n = b.next;
1162 dl 1.9 if (n == null)
1163 dl 1.1 return null;
1164     Node<K,V> f = n.next;
1165     if (n != b.next)
1166     continue;
1167     Object v = n.value;
1168     if (v == null) {
1169     n.helpDelete(b, f);
1170     continue;
1171     }
1172     if (!n.casValue(v, null))
1173     continue;
1174     if (!n.appendMarker(f) || !b.casNext(n, f))
1175     findFirst(); // retry
1176     clearIndexToFirst();
1177 dl 1.30 return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, (V)v);
1178 jsr166 1.28 }
1179 dl 1.1 }
1180    
1181     /**
1182 jsr166 1.10 * Clears out index nodes associated with deleted first entry.
1183 dl 1.1 */
1184     private void clearIndexToFirst() {
1185     for (;;) {
1186     Index<K,V> q = head;
1187     for (;;) {
1188     Index<K,V> r = q.right;
1189     if (r != null && r.indexesDeletedNode() && !q.unlink(r))
1190 dl 1.9 break;
1191 dl 1.1 if ((q = q.down) == null) {
1192 dl 1.9 if (head.right == null)
1193 dl 1.1 tryReduceLevel();
1194     return;
1195     }
1196     }
1197     }
1198     }
1199    
1200    
1201     /* ---------------- Finding and removing last element -------------- */
1202    
1203     /**
1204 jsr166 1.10 * Specialized version of find to get last valid node.
1205 dl 1.1 * @return last node or null if empty
1206     */
1207     Node<K,V> findLast() {
1208     /*
1209     * findPredecessor can't be used to traverse index level
1210     * because this doesn't use comparisons. So traversals of
1211     * both levels are folded together.
1212     */
1213     Index<K,V> q = head;
1214     for (;;) {
1215     Index<K,V> d, r;
1216     if ((r = q.right) != null) {
1217     if (r.indexesDeletedNode()) {
1218     q.unlink(r);
1219     q = head; // restart
1220 dl 1.9 }
1221 dl 1.1 else
1222     q = r;
1223     } else if ((d = q.down) != null) {
1224     q = d;
1225     } else {
1226     Node<K,V> b = q.node;
1227     Node<K,V> n = b.next;
1228     for (;;) {
1229 dl 1.9 if (n == null)
1230 dl 1.1 return (b.isBaseHeader())? null : b;
1231     Node<K,V> f = n.next; // inconsistent read
1232     if (n != b.next)
1233     break;
1234     Object v = n.value;
1235     if (v == null) { // n is deleted
1236     n.helpDelete(b, f);
1237     break;
1238     }
1239     if (v == n || b.value == null) // b is deleted
1240     break;
1241     b = n;
1242     n = f;
1243     }
1244     q = head; // restart
1245     }
1246     }
1247     }
1248    
1249 dl 1.31 /**
1250 jsr166 1.32 * Specialized variant of findPredecessor to get predecessor of last
1251     * valid node. Needed when removing the last entry. It is possible
1252     * that all successors of returned node will have been deleted upon
1253 dl 1.31 * return, in which case this method can be retried.
1254     * @return likely predecessor of last node
1255     */
1256     private Node<K,V> findPredecessorOfLast() {
1257     for (;;) {
1258     Index<K,V> q = head;
1259     for (;;) {
1260     Index<K,V> d, r;
1261     if ((r = q.right) != null) {
1262     if (r.indexesDeletedNode()) {
1263     q.unlink(r);
1264     break; // must restart
1265     }
1266     // proceed as far across as possible without overshooting
1267     if (r.node.next != null) {
1268     q = r;
1269     continue;
1270     }
1271     }
1272     if ((d = q.down) != null)
1273     q = d;
1274     else
1275     return q.node;
1276     }
1277     }
1278     }
1279 dl 1.1
1280     /**
1281 jsr166 1.32 * Removes last entry; returns its snapshot.
1282     * Specialized variant of doRemove.
1283     * @return null if empty, else snapshot of last entry
1284 dl 1.1 */
1285 dl 1.31 Map.Entry<K,V> doRemoveLastEntry() {
1286 dl 1.1 for (;;) {
1287 dl 1.31 Node<K,V> b = findPredecessorOfLast();
1288     Node<K,V> n = b.next;
1289     if (n == null) {
1290     if (b.isBaseHeader()) // empty
1291     return null;
1292     else
1293     continue; // all b's successors are deleted; retry
1294     }
1295 dl 1.1 for (;;) {
1296 dl 1.31 Node<K,V> f = n.next;
1297     if (n != b.next) // inconsistent read
1298     break;
1299     Object v = n.value;
1300     if (v == null) { // n is deleted
1301     n.helpDelete(b, f);
1302     break;
1303     }
1304     if (v == n || b.value == null) // b is deleted
1305     break;
1306     if (f != null) {
1307     b = n;
1308     n = f;
1309     continue;
1310     }
1311     if (!n.casValue(v, null))
1312     break;
1313     K key = n.key;
1314     Comparable<? super K> ck = comparable(key);
1315     if (!n.appendMarker(f) || !b.casNext(n, f))
1316     findNode(ck); // Retry via findNode
1317     else {
1318     findPredecessor(ck); // Clean index
1319     if (head.right == null)
1320     tryReduceLevel();
1321 dl 1.1 }
1322 dl 1.31 return new AbstractMap.SimpleImmutableEntry<K,V>(key, (V)v);
1323 dl 1.1 }
1324     }
1325     }
1326    
1327     /* ---------------- Relational operations -------------- */
1328    
1329     // Control values OR'ed as arguments to findNear
1330    
1331     private static final int EQ = 1;
1332     private static final int LT = 2;
1333     private static final int GT = 0; // Actually checked as !LT
1334    
1335     /**
1336     * Utility for ceiling, floor, lower, higher methods.
1337     * @param kkey the key
1338     * @param rel the relation -- OR'ed combination of EQ, LT, GT
1339     * @return nearest node fitting relation, or null if no such
1340     */
1341     Node<K,V> findNear(K kkey, int rel) {
1342 dl 1.9 Comparable<? super K> key = comparable(kkey);
1343 dl 1.1 for (;;) {
1344     Node<K,V> b = findPredecessor(key);
1345     Node<K,V> n = b.next;
1346     for (;;) {
1347 dl 1.9 if (n == null)
1348 dl 1.1 return ((rel & LT) == 0 || b.isBaseHeader())? null : b;
1349     Node<K,V> f = n.next;
1350     if (n != b.next) // inconsistent read
1351     break;
1352     Object v = n.value;
1353     if (v == null) { // n is deleted
1354     n.helpDelete(b, f);
1355     break;
1356     }
1357     if (v == n || b.value == null) // b is deleted
1358     break;
1359     int c = key.compareTo(n.key);
1360     if ((c == 0 && (rel & EQ) != 0) ||
1361     (c < 0 && (rel & LT) == 0))
1362     return n;
1363     if ( c <= 0 && (rel & LT) != 0)
1364     return (b.isBaseHeader())? null : b;
1365     b = n;
1366     n = f;
1367     }
1368     }
1369     }
1370    
1371     /**
1372 jsr166 1.10 * Returns SimpleImmutableEntry for results of findNear.
1373 dl 1.40 * @param key the key
1374 dl 1.1 * @param rel the relation -- OR'ed combination of EQ, LT, GT
1375     * @return Entry fitting relation, or null if no such
1376     */
1377 dl 1.40 AbstractMap.SimpleImmutableEntry<K,V> getNear(K key, int rel) {
1378 dl 1.1 for (;;) {
1379 dl 1.40 Node<K,V> n = findNear(key, rel);
1380 dl 1.1 if (n == null)
1381     return null;
1382 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
1383 dl 1.1 if (e != null)
1384     return e;
1385     }
1386     }
1387    
1388     /* ---------------- Constructors -------------- */
1389    
1390     /**
1391 jsr166 1.22 * Constructs a new, empty map, sorted according to the
1392     * {@linkplain Comparable natural ordering} of the keys.
1393 dl 1.1 */
1394     public ConcurrentSkipListMap() {
1395     this.comparator = null;
1396     initialize();
1397     }
1398    
1399     /**
1400 jsr166 1.22 * Constructs a new, empty map, sorted according to the specified
1401     * comparator.
1402 dl 1.1 *
1403 jsr166 1.22 * @param comparator the comparator that will be used to order this map.
1404     * If <tt>null</tt>, the {@linkplain Comparable natural
1405     * ordering} of the keys will be used.
1406 dl 1.1 */
1407 jsr166 1.22 public ConcurrentSkipListMap(Comparator<? super K> comparator) {
1408     this.comparator = comparator;
1409 dl 1.1 initialize();
1410     }
1411    
1412     /**
1413     * Constructs a new map containing the same mappings as the given map,
1414 jsr166 1.22 * sorted according to the {@linkplain Comparable natural ordering} of
1415     * the keys.
1416 dl 1.1 *
1417 jsr166 1.22 * @param m the map whose mappings are to be placed in this map
1418     * @throws ClassCastException if the keys in <tt>m</tt> are not
1419     * {@link Comparable}, or are not mutually comparable
1420     * @throws NullPointerException if the specified map or any of its keys
1421     * or values are null
1422 dl 1.1 */
1423     public ConcurrentSkipListMap(Map<? extends K, ? extends V> m) {
1424     this.comparator = null;
1425     initialize();
1426     putAll(m);
1427     }
1428    
1429     /**
1430 jsr166 1.22 * Constructs a new map containing the same mappings and using the
1431     * same ordering as the specified sorted map.
1432     *
1433 dl 1.1 * @param m the sorted map whose mappings are to be placed in this
1434 jsr166 1.22 * map, and whose comparator is to be used to sort this map
1435     * @throws NullPointerException if the specified sorted map or any of
1436     * its keys or values are null
1437 dl 1.1 */
1438     public ConcurrentSkipListMap(SortedMap<K, ? extends V> m) {
1439     this.comparator = m.comparator();
1440     initialize();
1441     buildFromSorted(m);
1442     }
1443    
1444     /**
1445 jsr166 1.22 * Returns a shallow copy of this <tt>ConcurrentSkipListMap</tt>
1446     * instance. (The keys and values themselves are not cloned.)
1447 dl 1.1 *
1448 jsr166 1.22 * @return a shallow copy of this map
1449 dl 1.1 */
1450 jsr166 1.16 public ConcurrentSkipListMap<K,V> clone() {
1451 dl 1.1 ConcurrentSkipListMap<K,V> clone = null;
1452     try {
1453     clone = (ConcurrentSkipListMap<K,V>) super.clone();
1454     } catch (CloneNotSupportedException e) {
1455     throw new InternalError();
1456     }
1457    
1458     clone.initialize();
1459     clone.buildFromSorted(this);
1460     return clone;
1461     }
1462    
1463     /**
1464     * Streamlined bulk insertion to initialize from elements of
1465     * given sorted map. Call only from constructor or clone
1466     * method.
1467     */
1468     private void buildFromSorted(SortedMap<K, ? extends V> map) {
1469     if (map == null)
1470     throw new NullPointerException();
1471    
1472     HeadIndex<K,V> h = head;
1473     Node<K,V> basepred = h.node;
1474    
1475     // Track the current rightmost node at each level. Uses an
1476     // ArrayList to avoid committing to initial or maximum level.
1477     ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1478    
1479     // initialize
1480 dl 1.9 for (int i = 0; i <= h.level; ++i)
1481 dl 1.1 preds.add(null);
1482     Index<K,V> q = h;
1483     for (int i = h.level; i > 0; --i) {
1484     preds.set(i, q);
1485     q = q.down;
1486     }
1487    
1488 dl 1.9 Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
1489 dl 1.1 map.entrySet().iterator();
1490     while (it.hasNext()) {
1491     Map.Entry<? extends K, ? extends V> e = it.next();
1492     int j = randomLevel();
1493     if (j > h.level) j = h.level + 1;
1494     K k = e.getKey();
1495     V v = e.getValue();
1496     if (k == null || v == null)
1497     throw new NullPointerException();
1498     Node<K,V> z = new Node<K,V>(k, v, null);
1499     basepred.next = z;
1500     basepred = z;
1501     if (j > 0) {
1502     Index<K,V> idx = null;
1503     for (int i = 1; i <= j; ++i) {
1504     idx = new Index<K,V>(z, idx, null);
1505 dl 1.9 if (i > h.level)
1506 dl 1.1 h = new HeadIndex<K,V>(h.node, h, idx, i);
1507    
1508     if (i < preds.size()) {
1509     preds.get(i).right = idx;
1510     preds.set(i, idx);
1511     } else
1512     preds.add(idx);
1513     }
1514     }
1515     }
1516     head = h;
1517     }
1518    
1519     /* ---------------- Serialization -------------- */
1520    
1521     /**
1522 jsr166 1.10 * Save the state of this map to a stream.
1523 dl 1.1 *
1524     * @serialData The key (Object) and value (Object) for each
1525 jsr166 1.10 * key-value mapping represented by the map, followed by
1526 dl 1.1 * <tt>null</tt>. The key-value mappings are emitted in key-order
1527     * (as determined by the Comparator, or by the keys' natural
1528     * ordering if no Comparator).
1529     */
1530     private void writeObject(java.io.ObjectOutputStream s)
1531     throws java.io.IOException {
1532     // Write out the Comparator and any hidden stuff
1533     s.defaultWriteObject();
1534    
1535     // Write out keys and values (alternating)
1536     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1537     V v = n.getValidValue();
1538     if (v != null) {
1539     s.writeObject(n.key);
1540     s.writeObject(v);
1541     }
1542     }
1543     s.writeObject(null);
1544     }
1545    
1546     /**
1547 jsr166 1.10 * Reconstitute the map from a stream.
1548 dl 1.1 */
1549     private void readObject(final java.io.ObjectInputStream s)
1550     throws java.io.IOException, ClassNotFoundException {
1551     // Read in the Comparator and any hidden stuff
1552     s.defaultReadObject();
1553     // Reset transients
1554     initialize();
1555    
1556 dl 1.9 /*
1557 dl 1.1 * This is nearly identical to buildFromSorted, but is
1558     * distinct because readObject calls can't be nicely adapted
1559     * as the kind of iterator needed by buildFromSorted. (They
1560     * can be, but doing so requires type cheats and/or creation
1561     * of adaptor classes.) It is simpler to just adapt the code.
1562     */
1563    
1564     HeadIndex<K,V> h = head;
1565     Node<K,V> basepred = h.node;
1566     ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
1567 dl 1.9 for (int i = 0; i <= h.level; ++i)
1568 dl 1.1 preds.add(null);
1569     Index<K,V> q = h;
1570     for (int i = h.level; i > 0; --i) {
1571     preds.set(i, q);
1572     q = q.down;
1573     }
1574    
1575     for (;;) {
1576     Object k = s.readObject();
1577     if (k == null)
1578     break;
1579     Object v = s.readObject();
1580 dl 1.9 if (v == null)
1581 dl 1.1 throw new NullPointerException();
1582     K key = (K) k;
1583     V val = (V) v;
1584     int j = randomLevel();
1585     if (j > h.level) j = h.level + 1;
1586     Node<K,V> z = new Node<K,V>(key, val, null);
1587     basepred.next = z;
1588     basepred = z;
1589     if (j > 0) {
1590     Index<K,V> idx = null;
1591     for (int i = 1; i <= j; ++i) {
1592     idx = new Index<K,V>(z, idx, null);
1593 dl 1.9 if (i > h.level)
1594 dl 1.1 h = new HeadIndex<K,V>(h.node, h, idx, i);
1595    
1596     if (i < preds.size()) {
1597     preds.get(i).right = idx;
1598     preds.set(i, idx);
1599     } else
1600     preds.add(idx);
1601     }
1602     }
1603     }
1604     head = h;
1605     }
1606    
1607     /* ------ Map API methods ------ */
1608    
1609     /**
1610     * Returns <tt>true</tt> if this map contains a mapping for the specified
1611     * key.
1612 jsr166 1.22 *
1613     * @param key key whose presence in this map is to be tested
1614     * @return <tt>true</tt> if this map contains a mapping for the specified key
1615     * @throws ClassCastException if the specified key cannot be compared
1616     * with the keys currently in the map
1617     * @throws NullPointerException if the specified key is null
1618 dl 1.1 */
1619     public boolean containsKey(Object key) {
1620     return doGet(key) != null;
1621     }
1622    
1623     /**
1624 jsr166 1.42 * Returns the value to which the specified key is mapped,
1625     * or {@code null} if this map contains no mapping for the key.
1626     *
1627     * <p>More formally, if this map contains a mapping from a key
1628     * {@code k} to a value {@code v} such that {@code key} compares
1629     * equal to {@code k} according to the map's ordering, then this
1630     * method returns {@code v}; otherwise it returns {@code null}.
1631     * (There can be at most one such mapping.)
1632 dl 1.1 *
1633 jsr166 1.22 * @throws ClassCastException if the specified key cannot be compared
1634     * with the keys currently in the map
1635     * @throws NullPointerException if the specified key is null
1636 dl 1.1 */
1637     public V get(Object key) {
1638     return doGet(key);
1639     }
1640    
1641     /**
1642     * Associates the specified value with the specified key in this map.
1643 jsr166 1.22 * If the map previously contained a mapping for the key, the old
1644 dl 1.1 * value is replaced.
1645     *
1646 jsr166 1.22 * @param key key with which the specified value is to be associated
1647     * @param value value to be associated with the specified key
1648     * @return the previous value associated with the specified key, or
1649     * <tt>null</tt> if there was no mapping for the key
1650     * @throws ClassCastException if the specified key cannot be compared
1651     * with the keys currently in the map
1652     * @throws NullPointerException if the specified key or value is null
1653 dl 1.1 */
1654     public V put(K key, V value) {
1655 dl 1.9 if (value == null)
1656 dl 1.1 throw new NullPointerException();
1657     return doPut(key, value, false);
1658     }
1659    
1660     /**
1661 jsr166 1.36 * Removes the mapping for the specified key from this map if present.
1662 dl 1.1 *
1663     * @param key key for which mapping should be removed
1664 jsr166 1.22 * @return the previous value associated with the specified key, or
1665     * <tt>null</tt> if there was no mapping for the key
1666     * @throws ClassCastException if the specified key cannot be compared
1667     * with the keys currently in the map
1668     * @throws NullPointerException if the specified key is null
1669 dl 1.1 */
1670     public V remove(Object key) {
1671     return doRemove(key, null);
1672     }
1673    
1674     /**
1675     * Returns <tt>true</tt> if this map maps one or more keys to the
1676     * specified value. This operation requires time linear in the
1677 jsr166 1.10 * map size.
1678 dl 1.1 *
1679 jsr166 1.22 * @param value value whose presence in this map is to be tested
1680     * @return <tt>true</tt> if a mapping to <tt>value</tt> exists;
1681     * <tt>false</tt> otherwise
1682     * @throws NullPointerException if the specified value is null
1683 dl 1.9 */
1684 dl 1.1 public boolean containsValue(Object value) {
1685 dl 1.9 if (value == null)
1686 dl 1.1 throw new NullPointerException();
1687     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1688     V v = n.getValidValue();
1689     if (v != null && value.equals(v))
1690     return true;
1691     }
1692     return false;
1693     }
1694    
1695     /**
1696 dl 1.6 * Returns the number of key-value mappings in this map. If this map
1697 dl 1.1 * contains more than <tt>Integer.MAX_VALUE</tt> elements, it
1698     * returns <tt>Integer.MAX_VALUE</tt>.
1699     *
1700     * <p>Beware that, unlike in most collections, this method is
1701     * <em>NOT</em> a constant-time operation. Because of the
1702     * asynchronous nature of these maps, determining the current
1703     * number of elements requires traversing them all to count them.
1704     * Additionally, it is possible for the size to change during
1705     * execution of this method, in which case the returned result
1706     * will be inaccurate. Thus, this method is typically not very
1707     * useful in concurrent applications.
1708     *
1709 jsr166 1.22 * @return the number of elements in this map
1710 dl 1.1 */
1711     public int size() {
1712     long count = 0;
1713     for (Node<K,V> n = findFirst(); n != null; n = n.next) {
1714     if (n.getValidValue() != null)
1715     ++count;
1716     }
1717     return (count >= Integer.MAX_VALUE)? Integer.MAX_VALUE : (int)count;
1718     }
1719    
1720     /**
1721     * Returns <tt>true</tt> if this map contains no key-value mappings.
1722 jsr166 1.22 * @return <tt>true</tt> if this map contains no key-value mappings
1723 dl 1.1 */
1724     public boolean isEmpty() {
1725     return findFirst() == null;
1726     }
1727    
1728     /**
1729 jsr166 1.22 * Removes all of the mappings from this map.
1730 dl 1.1 */
1731     public void clear() {
1732     initialize();
1733     }
1734    
1735 dl 1.46 /* ---------------- View methods -------------- */
1736    
1737     /*
1738     * Note: Lazy initialization works for views because view classes
1739     * are stateless/immutable so it doesn't matter wrt correctness if
1740     * more than one is created (which will only rarely happen). Even
1741     * so, the following idiom conservatively ensures that the method
1742     * returns the one it created if it does so, not one created by
1743     * another racing thread.
1744     */
1745    
1746 dl 1.1 /**
1747 jsr166 1.51 * Returns a {@link NavigableSet} view of the keys contained in this map.
1748 jsr166 1.22 * The set's iterator returns the keys in ascending order.
1749     * The set is backed by the map, so changes to the map are
1750     * reflected in the set, and vice-versa. The set supports element
1751     * removal, which removes the corresponding mapping from the map,
1752 jsr166 1.51 * via the {@code Iterator.remove}, {@code Set.remove},
1753     * {@code removeAll}, {@code retainAll}, and {@code clear}
1754     * operations. It does not support the {@code add} or {@code addAll}
1755 jsr166 1.22 * operations.
1756     *
1757 jsr166 1.51 * <p>The view's {@code iterator} is a "weakly consistent" iterator
1758 jsr166 1.22 * that will never throw {@link ConcurrentModificationException},
1759 dl 1.1 * and guarantees to traverse elements as they existed upon
1760     * construction of the iterator, and may (but is not guaranteed to)
1761     * reflect any modifications subsequent to construction.
1762     *
1763 jsr166 1.51 * <p>This method is equivalent to method {@code navigableKeySet}.
1764     *
1765     * @return a navigable set view of the keys in this map
1766 dl 1.1 */
1767 jsr166 1.51 public NavigableSet<K> keySet() {
1768 dl 1.1 KeySet ks = keySet;
1769 dl 1.46 return (ks != null) ? ks : (keySet = new KeySet(this));
1770 dl 1.1 }
1771    
1772 dl 1.46 public NavigableSet<K> navigableKeySet() {
1773     KeySet ks = keySet;
1774     return (ks != null) ? ks : (keySet = new KeySet(this));
1775 dl 1.1 }
1776    
1777     /**
1778 jsr166 1.22 * Returns a {@link Collection} view of the values contained in this map.
1779     * The collection's iterator returns the values in ascending order
1780     * of the corresponding keys.
1781 dl 1.1 * The collection is backed by the map, so changes to the map are
1782     * reflected in the collection, and vice-versa. The collection
1783     * supports element removal, which removes the corresponding
1784 jsr166 1.22 * mapping from the map, via the <tt>Iterator.remove</tt>,
1785 dl 1.1 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1786 jsr166 1.22 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1787     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1788 dl 1.1 *
1789 jsr166 1.22 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1790     * that will never throw {@link ConcurrentModificationException},
1791     * and guarantees to traverse elements as they existed upon
1792     * construction of the iterator, and may (but is not guaranteed to)
1793     * reflect any modifications subsequent to construction.
1794 dl 1.1 */
1795     public Collection<V> values() {
1796     Values vs = values;
1797 dl 1.46 return (vs != null) ? vs : (values = new Values(this));
1798 dl 1.1 }
1799    
1800     /**
1801 jsr166 1.22 * Returns a {@link Set} view of the mappings contained in this map.
1802     * The set's iterator returns the entries in ascending key order.
1803     * The set is backed by the map, so changes to the map are
1804     * reflected in the set, and vice-versa. The set supports element
1805     * removal, which removes the corresponding mapping from the map,
1806     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1807     * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1808 dl 1.1 * operations. It does not support the <tt>add</tt> or
1809 jsr166 1.22 * <tt>addAll</tt> operations.
1810     *
1811     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1812     * that will never throw {@link ConcurrentModificationException},
1813     * and guarantees to traverse elements as they existed upon
1814     * construction of the iterator, and may (but is not guaranteed to)
1815     * reflect any modifications subsequent to construction.
1816     *
1817     * <p>The <tt>Map.Entry</tt> elements returned by
1818 dl 1.1 * <tt>iterator.next()</tt> do <em>not</em> support the
1819     * <tt>setValue</tt> operation.
1820     *
1821 jsr166 1.22 * @return a set view of the mappings contained in this map,
1822     * sorted in ascending key order
1823 dl 1.1 */
1824     public Set<Map.Entry<K,V>> entrySet() {
1825     EntrySet es = entrySet;
1826 dl 1.46 return (es != null) ? es : (entrySet = new EntrySet(this));
1827     }
1828    
1829     public ConcurrentNavigableMap<K,V> descendingMap() {
1830     ConcurrentNavigableMap<K,V> dm = descendingMap;
1831     return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
1832     (this, null, false, null, false, true));
1833 dl 1.1 }
1834    
1835 dl 1.46 public NavigableSet<K> descendingKeySet() {
1836     return descendingMap().navigableKeySet();
1837 dl 1.1 }
1838    
1839     /* ---------------- AbstractMap Overrides -------------- */
1840    
1841     /**
1842     * Compares the specified object with this map for equality.
1843     * Returns <tt>true</tt> if the given object is also a map and the
1844     * two maps represent the same mappings. More formally, two maps
1845 jsr166 1.22 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
1846 jsr166 1.39 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This
1847 dl 1.1 * operation may return misleading results if either map is
1848     * concurrently modified during execution of this method.
1849     *
1850 jsr166 1.22 * @param o object to be compared for equality with this map
1851     * @return <tt>true</tt> if the specified object is equal to this map
1852 dl 1.1 */
1853     public boolean equals(Object o) {
1854     if (o == this)
1855     return true;
1856     if (!(o instanceof Map))
1857     return false;
1858 dl 1.25 Map<?,?> m = (Map<?,?>) o;
1859 dl 1.1 try {
1860 dl 1.25 for (Map.Entry<K,V> e : this.entrySet())
1861     if (! e.getValue().equals(m.get(e.getKey())))
1862     return false;
1863     for (Map.Entry<?,?> e : m.entrySet()) {
1864     Object k = e.getKey();
1865     Object v = e.getValue();
1866     if (k == null || v == null || !v.equals(get(k)))
1867     return false;
1868     }
1869     return true;
1870 jsr166 1.15 } catch (ClassCastException unused) {
1871 dl 1.1 return false;
1872 jsr166 1.15 } catch (NullPointerException unused) {
1873 dl 1.1 return false;
1874     }
1875     }
1876    
1877     /* ------ ConcurrentMap API methods ------ */
1878    
1879     /**
1880 jsr166 1.22 * {@inheritDoc}
1881     *
1882     * @return the previous value associated with the specified key,
1883     * or <tt>null</tt> if there was no mapping for the key
1884     * @throws ClassCastException if the specified key cannot be compared
1885     * with the keys currently in the map
1886     * @throws NullPointerException if the specified key or value is null
1887 dl 1.1 */
1888     public V putIfAbsent(K key, V value) {
1889 dl 1.9 if (value == null)
1890 dl 1.1 throw new NullPointerException();
1891     return doPut(key, value, true);
1892     }
1893    
1894     /**
1895 jsr166 1.22 * {@inheritDoc}
1896     *
1897     * @throws ClassCastException if the specified key cannot be compared
1898     * with the keys currently in the map
1899 dl 1.23 * @throws NullPointerException if the specified key is null
1900 dl 1.1 */
1901     public boolean remove(Object key, Object value) {
1902 dl 1.45 if (key == null)
1903     throw new NullPointerException();
1904 dl 1.9 if (value == null)
1905 dl 1.23 return false;
1906 dl 1.1 return doRemove(key, value) != null;
1907     }
1908    
1909     /**
1910 jsr166 1.22 * {@inheritDoc}
1911     *
1912     * @throws ClassCastException if the specified key cannot be compared
1913     * with the keys currently in the map
1914     * @throws NullPointerException if any of the arguments are null
1915 dl 1.1 */
1916     public boolean replace(K key, V oldValue, V newValue) {
1917 dl 1.9 if (oldValue == null || newValue == null)
1918 dl 1.1 throw new NullPointerException();
1919 dl 1.9 Comparable<? super K> k = comparable(key);
1920 dl 1.1 for (;;) {
1921     Node<K,V> n = findNode(k);
1922     if (n == null)
1923     return false;
1924     Object v = n.value;
1925     if (v != null) {
1926     if (!oldValue.equals(v))
1927     return false;
1928     if (n.casValue(v, newValue))
1929     return true;
1930     }
1931     }
1932     }
1933    
1934     /**
1935 jsr166 1.22 * {@inheritDoc}
1936     *
1937     * @return the previous value associated with the specified key,
1938     * or <tt>null</tt> if there was no mapping for the key
1939     * @throws ClassCastException if the specified key cannot be compared
1940     * with the keys currently in the map
1941     * @throws NullPointerException if the specified key or value is null
1942 dl 1.1 */
1943     public V replace(K key, V value) {
1944 dl 1.9 if (value == null)
1945 dl 1.1 throw new NullPointerException();
1946 dl 1.9 Comparable<? super K> k = comparable(key);
1947 dl 1.1 for (;;) {
1948     Node<K,V> n = findNode(k);
1949     if (n == null)
1950     return null;
1951     Object v = n.value;
1952     if (v != null && n.casValue(v, value))
1953     return (V)v;
1954     }
1955     }
1956    
1957     /* ------ SortedMap API methods ------ */
1958    
1959     public Comparator<? super K> comparator() {
1960     return comparator;
1961     }
1962    
1963     /**
1964 jsr166 1.22 * @throws NoSuchElementException {@inheritDoc}
1965 dl 1.1 */
1966 dl 1.9 public K firstKey() {
1967 dl 1.1 Node<K,V> n = findFirst();
1968     if (n == null)
1969     throw new NoSuchElementException();
1970     return n.key;
1971     }
1972    
1973     /**
1974 jsr166 1.22 * @throws NoSuchElementException {@inheritDoc}
1975 dl 1.1 */
1976     public K lastKey() {
1977     Node<K,V> n = findLast();
1978     if (n == null)
1979     throw new NoSuchElementException();
1980     return n.key;
1981     }
1982    
1983     /**
1984 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
1985     * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
1986 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
1987 dl 1.1 */
1988 dl 1.47 public ConcurrentNavigableMap<K,V> subMap(K fromKey,
1989     boolean fromInclusive,
1990     K toKey,
1991     boolean toInclusive) {
1992 dl 1.1 if (fromKey == null || toKey == null)
1993     throw new NullPointerException();
1994 dl 1.46 return new SubMap<K,V>
1995     (this, fromKey, fromInclusive, toKey, toInclusive, false);
1996 dl 1.1 }
1997    
1998     /**
1999 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
2000     * @throws NullPointerException if {@code toKey} is null
2001 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
2002 dl 1.1 */
2003 dl 1.47 public ConcurrentNavigableMap<K,V> headMap(K toKey,
2004     boolean inclusive) {
2005 dl 1.1 if (toKey == null)
2006     throw new NullPointerException();
2007 dl 1.46 return new SubMap<K,V>
2008     (this, null, false, toKey, inclusive, false);
2009 dl 1.1 }
2010    
2011     /**
2012 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
2013     * @throws NullPointerException if {@code fromKey} is null
2014 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
2015 dl 1.1 */
2016 dl 1.47 public ConcurrentNavigableMap<K,V> tailMap(K fromKey,
2017     boolean inclusive) {
2018 dl 1.6 if (fromKey == null)
2019     throw new NullPointerException();
2020 dl 1.46 return new SubMap<K,V>
2021     (this, fromKey, inclusive, null, false, false);
2022 dl 1.6 }
2023    
2024     /**
2025 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
2026     * @throws NullPointerException if {@code fromKey} or {@code toKey} is null
2027 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
2028 dl 1.6 */
2029 dl 1.37 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2030 dl 1.47 return subMap(fromKey, true, toKey, false);
2031 dl 1.6 }
2032    
2033     /**
2034 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
2035     * @throws NullPointerException if {@code toKey} is null
2036 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
2037 dl 1.6 */
2038 dl 1.37 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2039 dl 1.47 return headMap(toKey, false);
2040 dl 1.6 }
2041    
2042     /**
2043 jsr166 1.49 * @throws ClassCastException {@inheritDoc}
2044     * @throws NullPointerException if {@code fromKey} is null
2045 jsr166 1.22 * @throws IllegalArgumentException {@inheritDoc}
2046 dl 1.6 */
2047 dl 1.37 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2048 dl 1.47 return tailMap(fromKey, true);
2049 dl 1.1 }
2050    
2051     /* ---------------- Relational operations -------------- */
2052    
2053     /**
2054 jsr166 1.22 * Returns a key-value mapping associated with the greatest key
2055     * strictly less than the given key, or <tt>null</tt> if there is
2056     * no such key. The returned entry does <em>not</em> support the
2057     * <tt>Entry.setValue</tt> method.
2058 dl 1.9 *
2059 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2060     * @throws NullPointerException if the specified key is null
2061 dl 1.1 */
2062 jsr166 1.22 public Map.Entry<K,V> lowerEntry(K key) {
2063     return getNear(key, LT);
2064 dl 1.1 }
2065    
2066     /**
2067 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2068     * @throws NullPointerException if the specified key is null
2069 dl 1.1 */
2070 jsr166 1.22 public K lowerKey(K key) {
2071     Node<K,V> n = findNear(key, LT);
2072 dl 1.1 return (n == null)? null : n.key;
2073     }
2074    
2075     /**
2076 jsr166 1.22 * Returns a key-value mapping associated with the greatest key
2077     * less than or equal to the given key, or <tt>null</tt> if there
2078     * is no such key. The returned entry does <em>not</em> support
2079 dl 1.1 * the <tt>Entry.setValue</tt> method.
2080 dl 1.9 *
2081 jsr166 1.22 * @param key the key
2082     * @throws ClassCastException {@inheritDoc}
2083     * @throws NullPointerException if the specified key is null
2084 dl 1.1 */
2085 jsr166 1.22 public Map.Entry<K,V> floorEntry(K key) {
2086     return getNear(key, LT|EQ);
2087 dl 1.1 }
2088    
2089     /**
2090 jsr166 1.22 * @param key the key
2091     * @throws ClassCastException {@inheritDoc}
2092     * @throws NullPointerException if the specified key is null
2093 dl 1.1 */
2094 jsr166 1.22 public K floorKey(K key) {
2095     Node<K,V> n = findNear(key, LT|EQ);
2096 dl 1.1 return (n == null)? null : n.key;
2097     }
2098    
2099     /**
2100 jsr166 1.22 * Returns a key-value mapping associated with the least key
2101     * greater than or equal to the given key, or <tt>null</tt> if
2102     * there is no such entry. The returned entry does <em>not</em>
2103     * support the <tt>Entry.setValue</tt> method.
2104 dl 1.9 *
2105 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2106     * @throws NullPointerException if the specified key is null
2107 dl 1.1 */
2108 jsr166 1.22 public Map.Entry<K,V> ceilingEntry(K key) {
2109     return getNear(key, GT|EQ);
2110 dl 1.1 }
2111    
2112     /**
2113 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2114     * @throws NullPointerException if the specified key is null
2115 dl 1.1 */
2116 jsr166 1.22 public K ceilingKey(K key) {
2117     Node<K,V> n = findNear(key, GT|EQ);
2118 dl 1.1 return (n == null)? null : n.key;
2119     }
2120    
2121     /**
2122     * Returns a key-value mapping associated with the least key
2123     * strictly greater than the given key, or <tt>null</tt> if there
2124 jsr166 1.22 * is no such key. The returned entry does <em>not</em> support
2125 dl 1.1 * the <tt>Entry.setValue</tt> method.
2126 dl 1.9 *
2127 jsr166 1.22 * @param key the key
2128     * @throws ClassCastException {@inheritDoc}
2129     * @throws NullPointerException if the specified key is null
2130 dl 1.1 */
2131     public Map.Entry<K,V> higherEntry(K key) {
2132     return getNear(key, GT);
2133     }
2134    
2135     /**
2136 jsr166 1.22 * @param key the key
2137     * @throws ClassCastException {@inheritDoc}
2138     * @throws NullPointerException if the specified key is null
2139 dl 1.1 */
2140     public K higherKey(K key) {
2141     Node<K,V> n = findNear(key, GT);
2142     return (n == null)? null : n.key;
2143     }
2144    
2145     /**
2146     * Returns a key-value mapping associated with the least
2147     * key in this map, or <tt>null</tt> if the map is empty.
2148     * The returned entry does <em>not</em> support
2149     * the <tt>Entry.setValue</tt> method.
2150     */
2151     public Map.Entry<K,V> firstEntry() {
2152     for (;;) {
2153     Node<K,V> n = findFirst();
2154 dl 1.9 if (n == null)
2155 dl 1.1 return null;
2156 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2157 dl 1.1 if (e != null)
2158     return e;
2159     }
2160     }
2161    
2162     /**
2163     * Returns a key-value mapping associated with the greatest
2164     * key in this map, or <tt>null</tt> if the map is empty.
2165     * The returned entry does <em>not</em> support
2166     * the <tt>Entry.setValue</tt> method.
2167     */
2168     public Map.Entry<K,V> lastEntry() {
2169     for (;;) {
2170     Node<K,V> n = findLast();
2171 dl 1.9 if (n == null)
2172 dl 1.1 return null;
2173 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2174 dl 1.1 if (e != null)
2175     return e;
2176     }
2177     }
2178    
2179     /**
2180     * Removes and returns a key-value mapping associated with
2181     * the least key in this map, or <tt>null</tt> if the map is empty.
2182     * The returned entry does <em>not</em> support
2183     * the <tt>Entry.setValue</tt> method.
2184     */
2185     public Map.Entry<K,V> pollFirstEntry() {
2186 dl 1.25 return doRemoveFirstEntry();
2187 dl 1.1 }
2188    
2189     /**
2190     * Removes and returns a key-value mapping associated with
2191     * the greatest key in this map, or <tt>null</tt> if the map is empty.
2192     * The returned entry does <em>not</em> support
2193     * the <tt>Entry.setValue</tt> method.
2194     */
2195     public Map.Entry<K,V> pollLastEntry() {
2196 dl 1.31 return doRemoveLastEntry();
2197 dl 1.1 }
2198    
2199    
2200     /* ---------------- Iterators -------------- */
2201    
2202     /**
2203 dl 1.46 * Base of iterator classes:
2204 dl 1.1 */
2205 dl 1.46 abstract class Iter<T> implements Iterator<T> {
2206 dl 1.1 /** the last node returned by next() */
2207     Node<K,V> last;
2208     /** the next node to return from next(); */
2209     Node<K,V> next;
2210     /** Cache of next value field to maintain weak consistency */
2211     Object nextValue;
2212    
2213 jsr166 1.13 /** Initializes ascending iterator for entire range. */
2214 dl 1.46 Iter() {
2215 dl 1.1 for (;;) {
2216     next = findFirst();
2217     if (next == null)
2218     break;
2219     nextValue = next.value;
2220     if (nextValue != null && nextValue != next)
2221     break;
2222     }
2223     }
2224    
2225 dl 1.46 public final boolean hasNext() {
2226     return next != null;
2227 dl 1.1 }
2228 dl 1.46
2229 jsr166 1.13 /** Advances next to higher entry. */
2230 dl 1.46 final void advance() {
2231 dl 1.1 if ((last = next) == null)
2232     throw new NoSuchElementException();
2233     for (;;) {
2234     next = next.next;
2235     if (next == null)
2236     break;
2237     nextValue = next.value;
2238     if (nextValue != null && nextValue != next)
2239     break;
2240     }
2241     }
2242    
2243     public void remove() {
2244     Node<K,V> l = last;
2245     if (l == null)
2246     throw new IllegalStateException();
2247     // It would not be worth all of the overhead to directly
2248     // unlink from here. Using remove is fast enough.
2249     ConcurrentSkipListMap.this.remove(l.key);
2250     }
2251    
2252     }
2253    
2254 dl 1.46 final class ValueIterator extends Iter<V> {
2255 dl 1.9 public V next() {
2256 dl 1.1 Object v = nextValue;
2257 dl 1.46 advance();
2258 dl 1.1 return (V)v;
2259     }
2260     }
2261    
2262 dl 1.46 final class KeyIterator extends Iter<K> {
2263 dl 1.9 public K next() {
2264 dl 1.1 Node<K,V> n = next;
2265 dl 1.46 advance();
2266 dl 1.1 return n.key;
2267     }
2268     }
2269    
2270 dl 1.46 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2271     public Map.Entry<K,V> next() {
2272     Node<K,V> n = next;
2273     V v = (V)nextValue;
2274     advance();
2275     return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2276 dl 1.1 }
2277 dl 1.46 }
2278 dl 1.1
2279 dl 1.46 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2280    
2281     Iterator<K> keyIterator() {
2282 dl 1.1 return new KeyIterator();
2283     }
2284    
2285 dl 1.46 Iterator<V> valueIterator() {
2286     return new ValueIterator();
2287 dl 1.1 }
2288    
2289 dl 1.46 Iterator<Map.Entry<K,V>> entryIterator() {
2290     return new EntryIterator();
2291 dl 1.1 }
2292    
2293 dl 1.46 /* ---------------- View Classes -------------- */
2294    
2295     /*
2296     * View classes are static, delegating to a ConcurrentNavigableMap
2297     * to allow use by SubMaps, which outweighs the ugliness of
2298     * needing type-tests for Iterator methods.
2299     */
2300    
2301     static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
2302     private final ConcurrentNavigableMap<E,Object> m;
2303     KeySet(ConcurrentNavigableMap<E,Object> map) { m = map; }
2304     public int size() { return m.size(); }
2305     public boolean isEmpty() { return m.isEmpty(); }
2306     public boolean contains(Object o) { return m.containsKey(o); }
2307     public boolean remove(Object o) { return m.remove(o) != null; }
2308     public void clear() { m.clear(); }
2309     public E lower(E e) { return m.lowerKey(e); }
2310     public E floor(E e) { return m.floorKey(e); }
2311     public E ceiling(E e) { return m.ceilingKey(e); }
2312     public E higher(E e) { return m.higherKey(e); }
2313     public Comparator<? super E> comparator() { return m.comparator(); }
2314     public E first() { return m.firstKey(); }
2315     public E last() { return m.lastKey(); }
2316     public E pollFirst() {
2317     Map.Entry<E,Object> e = m.pollFirstEntry();
2318     return e == null? null : e.getKey();
2319     }
2320     public E pollLast() {
2321     Map.Entry<E,Object> e = m.pollLastEntry();
2322     return e == null? null : e.getKey();
2323     }
2324     public Iterator<E> iterator() {
2325     if (m instanceof ConcurrentSkipListMap)
2326     return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2327     else
2328     return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2329 dl 1.1 }
2330 dl 1.45 public boolean equals(Object o) {
2331     if (o == this)
2332     return true;
2333     if (!(o instanceof Set))
2334     return false;
2335     Collection<?> c = (Collection<?>) o;
2336     try {
2337     return containsAll(c) && c.containsAll(this);
2338     } catch (ClassCastException unused) {
2339     return false;
2340     } catch (NullPointerException unused) {
2341     return false;
2342     }
2343     }
2344 dl 1.46 public Iterator<E> descendingIterator() {
2345     return descendingSet().iterator();
2346     }
2347 dl 1.47 public NavigableSet<E> subSet(E fromElement,
2348     boolean fromInclusive,
2349     E toElement,
2350     boolean toInclusive) {
2351 dl 1.46 return new ConcurrentSkipListSet<E>
2352 dl 1.47 (m.subMap(fromElement, fromInclusive,
2353     toElement, toInclusive));
2354 dl 1.46 }
2355 dl 1.47 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
2356     return new ConcurrentSkipListSet<E>(m.headMap(toElement, inclusive));
2357 dl 1.46 }
2358 dl 1.47 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
2359     return new ConcurrentSkipListSet<E>(m.tailMap(fromElement, inclusive));
2360 dl 1.46 }
2361 jsr166 1.51 public NavigableSet<E> subSet(E fromElement, E toElement) {
2362 dl 1.47 return subSet(fromElement, true, toElement, false);
2363 dl 1.46 }
2364 jsr166 1.51 public NavigableSet<E> headSet(E toElement) {
2365 dl 1.47 return headSet(toElement, false);
2366 dl 1.46 }
2367 jsr166 1.51 public NavigableSet<E> tailSet(E fromElement) {
2368 dl 1.47 return tailSet(fromElement, true);
2369 dl 1.46 }
2370     public NavigableSet<E> descendingSet() {
2371     return new ConcurrentSkipListSet(m.descendingMap());
2372     }
2373 dl 1.1 }
2374    
2375 dl 1.46 static final class Values<E> extends AbstractCollection<E> {
2376     private final ConcurrentNavigableMap<Object, E> m;
2377     Values(ConcurrentNavigableMap<Object, E> map) {
2378     m = map;
2379 dl 1.1 }
2380 dl 1.46 public Iterator<E> iterator() {
2381     if (m instanceof ConcurrentSkipListMap)
2382     return ((ConcurrentSkipListMap<Object,E>)m).valueIterator();
2383     else
2384     return ((SubMap<Object,E>)m).valueIterator();
2385 dl 1.1 }
2386     public boolean isEmpty() {
2387 dl 1.46 return m.isEmpty();
2388 dl 1.1 }
2389     public int size() {
2390 dl 1.46 return m.size();
2391 dl 1.1 }
2392     public boolean contains(Object o) {
2393 dl 1.46 return m.containsValue(o);
2394 dl 1.1 }
2395     public void clear() {
2396 dl 1.46 m.clear();
2397 dl 1.1 }
2398     }
2399    
2400 dl 1.46 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2401     private final ConcurrentNavigableMap<K1, V1> m;
2402     EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2403     m = map;
2404 dl 1.1 }
2405 dl 1.46
2406     public Iterator<Map.Entry<K1,V1>> iterator() {
2407     if (m instanceof ConcurrentSkipListMap)
2408     return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2409     else
2410     return ((SubMap<K1,V1>)m).entryIterator();
2411     }
2412 dl 1.47
2413 dl 1.1 public boolean contains(Object o) {
2414     if (!(o instanceof Map.Entry))
2415     return false;
2416 dl 1.46 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2417     V1 v = m.get(e.getKey());
2418 dl 1.1 return v != null && v.equals(e.getValue());
2419     }
2420     public boolean remove(Object o) {
2421     if (!(o instanceof Map.Entry))
2422     return false;
2423 dl 1.46 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2424     return m.remove(e.getKey(),
2425 dl 1.47 e.getValue());
2426 dl 1.1 }
2427     public boolean isEmpty() {
2428 dl 1.46 return m.isEmpty();
2429 dl 1.1 }
2430     public int size() {
2431 dl 1.46 return m.size();
2432 dl 1.1 }
2433     public void clear() {
2434 dl 1.46 m.clear();
2435 dl 1.1 }
2436 dl 1.45 public boolean equals(Object o) {
2437     if (o == this)
2438     return true;
2439     if (!(o instanceof Set))
2440     return false;
2441     Collection<?> c = (Collection<?>) o;
2442     try {
2443     return containsAll(c) && c.containsAll(this);
2444     } catch (ClassCastException unused) {
2445     return false;
2446     } catch (NullPointerException unused) {
2447     return false;
2448     }
2449     }
2450 dl 1.1 }
2451    
2452     /**
2453     * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2454     * represent a subrange of mappings of their underlying
2455     * maps. Instances of this class support all methods of their
2456     * underlying maps, differing in that mappings outside their range are
2457     * ignored, and attempts to add mappings outside their ranges result
2458     * in {@link IllegalArgumentException}. Instances of this class are
2459     * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2460     * <tt>tailMap</tt> methods of their underlying maps.
2461     */
2462 dl 1.46 static final class SubMap<K,V> extends AbstractMap<K,V>
2463     implements ConcurrentNavigableMap<K,V>, Cloneable,
2464     java.io.Serializable {
2465 dl 1.1 private static final long serialVersionUID = -7647078645895051609L;
2466    
2467     /** Underlying map */
2468     private final ConcurrentSkipListMap<K,V> m;
2469     /** lower bound key, or null if from start */
2470 dl 1.46 private final K lo;
2471     /** upper bound key, or null if to end */
2472     private final K hi;
2473     /** inclusion flag for lo */
2474     private final boolean loInclusive;
2475     /** inclusion flag for hi */
2476     private final boolean hiInclusive;
2477     /** direction */
2478     private final boolean isDescending;
2479    
2480 dl 1.1 // Lazily initialized view holders
2481 dl 1.46 private transient KeySet<K> keySetView;
2482 dl 1.1 private transient Set<Map.Entry<K,V>> entrySetView;
2483     private transient Collection<V> valuesView;
2484    
2485     /**
2486 dl 1.46 * Creates a new submap, initializing all fields
2487     */
2488     SubMap(ConcurrentSkipListMap<K,V> map,
2489     K fromKey, boolean fromInclusive,
2490     K toKey, boolean toInclusive,
2491     boolean isDescending) {
2492 dl 1.47 if (fromKey != null && toKey != null &&
2493 dl 1.46 map.compare(fromKey, toKey) > 0)
2494 dl 1.1 throw new IllegalArgumentException("inconsistent range");
2495     this.m = map;
2496 dl 1.46 this.lo = fromKey;
2497     this.hi = toKey;
2498     this.loInclusive = fromInclusive;
2499     this.hiInclusive = toInclusive;
2500     this.isDescending = isDescending;
2501 dl 1.1 }
2502    
2503     /* ---------------- Utilities -------------- */
2504    
2505 dl 1.46 private boolean tooLow(K key) {
2506     if (lo != null) {
2507     int c = m.compare(key, lo);
2508     if (c < 0 || (c == 0 && !loInclusive))
2509     return true;
2510     }
2511     return false;
2512 dl 1.1 }
2513    
2514 dl 1.46 private boolean tooHigh(K key) {
2515     if (hi != null) {
2516     int c = m.compare(key, hi);
2517     if (c > 0 || (c == 0 && !hiInclusive))
2518     return true;
2519     }
2520     return false;
2521 dl 1.1 }
2522    
2523 dl 1.46 private boolean inBounds(K key) {
2524     return !tooLow(key) && !tooHigh(key);
2525 dl 1.1 }
2526    
2527 dl 1.46 private void checkKeyBounds(K key) throws IllegalArgumentException {
2528     if (key == null)
2529     throw new NullPointerException();
2530     if (!inBounds(key))
2531     throw new IllegalArgumentException("key out of range");
2532 dl 1.1 }
2533    
2534 dl 1.46 /**
2535     * Returns true if node key is less than upper bound of range
2536     */
2537     private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
2538     if (n == null)
2539     return false;
2540     if (hi == null)
2541     return true;
2542     K k = n.key;
2543     if (k == null) // pass by markers and headers
2544     return true;
2545     int c = m.compare(k, hi);
2546     if (c > 0 || (c == 0 && !hiInclusive))
2547     return false;
2548     return true;
2549 dl 1.1 }
2550    
2551 dl 1.46 /**
2552     * Returns lowest node. This node might not be in range, so
2553     * most usages need to check bounds
2554     */
2555     private ConcurrentSkipListMap.Node<K,V> loNode() {
2556     if (lo == null)
2557     return m.findFirst();
2558     else if (loInclusive)
2559     return m.findNear(lo, m.GT|m.EQ);
2560     else
2561     return m.findNear(lo, m.GT);
2562 dl 1.1 }
2563    
2564     /**
2565 dl 1.46 * Returns highest node. This node might not be in range, so
2566     * most usages need to check bounds
2567 dl 1.1 */
2568 dl 1.46 private ConcurrentSkipListMap.Node<K,V> hiNode() {
2569     if (hi == null)
2570     return m.findLast();
2571     else if (hiInclusive)
2572     return m.findNear(hi, m.LT|m.EQ);
2573     else
2574     return m.findNear(hi, m.LT);
2575 dl 1.1 }
2576    
2577     /**
2578 dl 1.46 * Returns lowest absolute key (ignoring directonality)
2579 dl 1.1 */
2580 dl 1.46 private K lowestKey() {
2581     ConcurrentSkipListMap.Node<K,V> n = loNode();
2582     if (isBeforeEnd(n))
2583     return n.key;
2584     else
2585     throw new NoSuchElementException();
2586 dl 1.47 }
2587 dl 1.46
2588     /**
2589     * Returns highest absolute key (ignoring directonality)
2590     */
2591     private K highestKey() {
2592     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2593     if (n != null) {
2594     K last = n.key;
2595     if (inBounds(last))
2596     return last;
2597     }
2598     throw new NoSuchElementException();
2599     }
2600    
2601     private Map.Entry<K,V> lowestEntry() {
2602     for (;;) {
2603     ConcurrentSkipListMap.Node<K,V> n = loNode();
2604     if (!isBeforeEnd(n))
2605     return null;
2606     Map.Entry<K,V> e = n.createSnapshot();
2607     if (e != null)
2608     return e;
2609     }
2610     }
2611    
2612     private Map.Entry<K,V> highestEntry() {
2613     for (;;) {
2614     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2615     if (n == null || !inBounds(n.key))
2616     return null;
2617     Map.Entry<K,V> e = n.createSnapshot();
2618     if (e != null)
2619     return e;
2620     }
2621     }
2622    
2623     private Map.Entry<K,V> removeLowest() {
2624     for (;;) {
2625     Node<K,V> n = loNode();
2626     if (n == null)
2627     return null;
2628     K k = n.key;
2629     if (!inBounds(k))
2630     return null;
2631     V v = m.doRemove(k, null);
2632     if (v != null)
2633     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2634     }
2635     }
2636    
2637     private Map.Entry<K,V> removeHighest() {
2638     for (;;) {
2639     Node<K,V> n = hiNode();
2640     if (n == null)
2641     return null;
2642     K k = n.key;
2643     if (!inBounds(k))
2644     return null;
2645     V v = m.doRemove(k, null);
2646     if (v != null)
2647     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2648     }
2649 dl 1.1 }
2650    
2651     /**
2652 dl 1.46 * Submap version of ConcurrentSkipListMap.getNearEntry
2653 dl 1.1 */
2654 dl 1.46 private Map.Entry<K,V> getNearEntry(K key, int rel) {
2655     if (isDescending) { // adjust relation for direction
2656     if ((rel & m.LT) == 0)
2657     rel |= m.LT;
2658     else
2659     rel &= ~m.LT;
2660     }
2661     if (tooLow(key))
2662     return ((rel & m.LT) != 0)? null : lowestEntry();
2663     if (tooHigh(key))
2664     return ((rel & m.LT) != 0)? highestEntry() : null;
2665     for (;;) {
2666     Node<K,V> n = m.findNear(key, rel);
2667     if (n == null || !inBounds(n.key))
2668     return null;
2669     K k = n.key;
2670     V v = n.getValidValue();
2671     if (v != null)
2672     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2673     }
2674 dl 1.1 }
2675    
2676 jsr166 1.48 // Almost the same as getNearEntry, except for keys
2677 dl 1.46 private K getNearKey(K key, int rel) {
2678     if (isDescending) { // adjust relation for direction
2679     if ((rel & m.LT) == 0)
2680     rel |= m.LT;
2681     else
2682     rel &= ~m.LT;
2683     }
2684     if (tooLow(key)) {
2685     if ((rel & m.LT) == 0) {
2686     ConcurrentSkipListMap.Node<K,V> n = loNode();
2687     if (isBeforeEnd(n))
2688     return n.key;
2689     }
2690     return null;
2691     }
2692     if (tooHigh(key)) {
2693     if ((rel & m.LT) != 0) {
2694     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2695     if (n != null) {
2696     K last = n.key;
2697     if (inBounds(last))
2698     return last;
2699     }
2700     }
2701     return null;
2702     }
2703     for (;;) {
2704     Node<K,V> n = m.findNear(key, rel);
2705     if (n == null || !inBounds(n.key))
2706     return null;
2707     K k = n.key;
2708     V v = n.getValidValue();
2709     if (v != null)
2710     return k;
2711     }
2712     }
2713 dl 1.1
2714     /* ---------------- Map API methods -------------- */
2715    
2716     public boolean containsKey(Object key) {
2717 dl 1.46 if (key == null) throw new NullPointerException();
2718 dl 1.1 K k = (K)key;
2719 dl 1.46 return inBounds(k) && m.containsKey(k);
2720 dl 1.1 }
2721    
2722     public V get(Object key) {
2723 dl 1.46 if (key == null) throw new NullPointerException();
2724 dl 1.1 K k = (K)key;
2725 dl 1.46 return ((!inBounds(k)) ? null : m.get(k));
2726 dl 1.1 }
2727    
2728     public V put(K key, V value) {
2729 dl 1.46 checkKeyBounds(key);
2730 dl 1.1 return m.put(key, value);
2731     }
2732    
2733     public V remove(Object key) {
2734     K k = (K)key;
2735 dl 1.46 return (!inBounds(k))? null : m.remove(k);
2736 dl 1.1 }
2737    
2738     public int size() {
2739     long count = 0;
2740 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2741 dl 1.9 isBeforeEnd(n);
2742 dl 1.1 n = n.next) {
2743     if (n.getValidValue() != null)
2744     ++count;
2745     }
2746     return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count;
2747     }
2748    
2749     public boolean isEmpty() {
2750 dl 1.46 return !isBeforeEnd(loNode());
2751 dl 1.1 }
2752    
2753     public boolean containsValue(Object value) {
2754 dl 1.9 if (value == null)
2755 dl 1.1 throw new NullPointerException();
2756 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2757 dl 1.9 isBeforeEnd(n);
2758 dl 1.1 n = n.next) {
2759     V v = n.getValidValue();
2760     if (v != null && value.equals(v))
2761     return true;
2762     }
2763     return false;
2764     }
2765    
2766     public void clear() {
2767 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2768 dl 1.9 isBeforeEnd(n);
2769 dl 1.1 n = n.next) {
2770     if (n.getValidValue() != null)
2771     m.remove(n.key);
2772     }
2773     }
2774    
2775     /* ---------------- ConcurrentMap API methods -------------- */
2776    
2777     public V putIfAbsent(K key, V value) {
2778 dl 1.46 checkKeyBounds(key);
2779 dl 1.1 return m.putIfAbsent(key, value);
2780     }
2781    
2782     public boolean remove(Object key, Object value) {
2783     K k = (K)key;
2784 dl 1.46 return inBounds(k) && m.remove(k, value);
2785 dl 1.1 }
2786    
2787     public boolean replace(K key, V oldValue, V newValue) {
2788 dl 1.46 checkKeyBounds(key);
2789 dl 1.1 return m.replace(key, oldValue, newValue);
2790     }
2791    
2792     public V replace(K key, V value) {
2793 dl 1.46 checkKeyBounds(key);
2794 dl 1.1 return m.replace(key, value);
2795     }
2796    
2797     /* ---------------- SortedMap API methods -------------- */
2798    
2799     public Comparator<? super K> comparator() {
2800 dl 1.46 Comparator<? super K> cmp = m.comparator();
2801     if (cmp == null || !isDescending)
2802     return cmp;
2803 dl 1.1 else
2804 dl 1.46 return Collections.reverseOrder(cmp);
2805 dl 1.1 }
2806 dl 1.47
2807 dl 1.46 /**
2808     * Utility to create submaps, where given bounds override
2809     * unbounded(null) ones and/or are checked against bounded ones.
2810     */
2811 dl 1.47 private SubMap<K,V> newSubMap(K fromKey,
2812     boolean fromInclusive,
2813     K toKey,
2814 dl 1.46 boolean toInclusive) {
2815     if (isDescending) { // flip senses
2816 dl 1.47 K tk = fromKey;
2817     fromKey = toKey;
2818 dl 1.46 toKey = tk;
2819 dl 1.47 boolean ti = fromInclusive;
2820     fromInclusive = toInclusive;
2821 dl 1.46 toInclusive = ti;
2822     }
2823     if (lo != null) {
2824     if (fromKey == null) {
2825     fromKey = lo;
2826     fromInclusive = loInclusive;
2827     }
2828     else {
2829     int c = m.compare(fromKey, lo);
2830     if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2831     throw new IllegalArgumentException("key out of range");
2832     }
2833     }
2834     if (hi != null) {
2835     if (toKey == null) {
2836     toKey = hi;
2837     toInclusive = hiInclusive;
2838     }
2839     else {
2840     int c = m.compare(toKey, hi);
2841     if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2842     throw new IllegalArgumentException("key out of range");
2843     }
2844 dl 1.1 }
2845 dl 1.47 return new SubMap<K,V>(m, fromKey, fromInclusive,
2846 dl 1.46 toKey, toInclusive, isDescending);
2847 dl 1.1 }
2848    
2849 dl 1.47 public SubMap<K,V> subMap(K fromKey,
2850     boolean fromInclusive,
2851     K toKey,
2852     boolean toInclusive) {
2853 dl 1.1 if (fromKey == null || toKey == null)
2854     throw new NullPointerException();
2855 dl 1.46 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2856 dl 1.1 }
2857 dl 1.47
2858     public SubMap<K,V> headMap(K toKey,
2859     boolean inclusive) {
2860 dl 1.1 if (toKey == null)
2861     throw new NullPointerException();
2862 dl 1.46 return newSubMap(null, false, toKey, inclusive);
2863 dl 1.1 }
2864 dl 1.47
2865     public SubMap<K,V> tailMap(K fromKey,
2866     boolean inclusive) {
2867 dl 1.1 if (fromKey == null)
2868     throw new NullPointerException();
2869 dl 1.46 return newSubMap(fromKey, inclusive, null, false);
2870     }
2871    
2872     public SubMap<K,V> subMap(K fromKey, K toKey) {
2873 dl 1.47 return subMap(fromKey, true, toKey, false);
2874 dl 1.1 }
2875    
2876 dl 1.46 public SubMap<K,V> headMap(K toKey) {
2877 dl 1.47 return headMap(toKey, false);
2878 dl 1.6 }
2879    
2880 dl 1.46 public SubMap<K,V> tailMap(K fromKey) {
2881 dl 1.47 return tailMap(fromKey, true);
2882 dl 1.6 }
2883    
2884 dl 1.46 public SubMap<K,V> descendingMap() {
2885 dl 1.47 return new SubMap<K,V>(m, lo, loInclusive,
2886 dl 1.46 hi, hiInclusive, !isDescending);
2887 dl 1.6 }
2888    
2889 dl 1.1 /* ---------------- Relational methods -------------- */
2890    
2891     public Map.Entry<K,V> ceilingEntry(K key) {
2892 dl 1.46 return getNearEntry(key, (m.GT|m.EQ));
2893 dl 1.1 }
2894    
2895     public K ceilingKey(K key) {
2896 dl 1.46 return getNearKey(key, (m.GT|m.EQ));
2897 dl 1.1 }
2898    
2899     public Map.Entry<K,V> lowerEntry(K key) {
2900 dl 1.46 return getNearEntry(key, (m.LT));
2901 dl 1.1 }
2902    
2903     public K lowerKey(K key) {
2904 dl 1.46 return getNearKey(key, (m.LT));
2905 dl 1.1 }
2906    
2907     public Map.Entry<K,V> floorEntry(K key) {
2908 dl 1.46 return getNearEntry(key, (m.LT|m.EQ));
2909 dl 1.1 }
2910    
2911     public K floorKey(K key) {
2912 dl 1.46 return getNearKey(key, (m.LT|m.EQ));
2913 dl 1.1 }
2914    
2915     public Map.Entry<K,V> higherEntry(K key) {
2916 dl 1.46 return getNearEntry(key, (m.GT));
2917 dl 1.1 }
2918    
2919     public K higherKey(K key) {
2920 dl 1.46 return getNearKey(key, (m.GT));
2921     }
2922    
2923     public K firstKey() {
2924     return isDescending? highestKey() : lowestKey();
2925     }
2926    
2927     public K lastKey() {
2928     return isDescending? lowestKey() : highestKey();
2929 dl 1.1 }
2930    
2931     public Map.Entry<K,V> firstEntry() {
2932 dl 1.46 return isDescending? highestEntry() : lowestEntry();
2933 dl 1.1 }
2934    
2935     public Map.Entry<K,V> lastEntry() {
2936 dl 1.46 return isDescending? lowestEntry() : highestEntry();
2937 dl 1.1 }
2938    
2939     public Map.Entry<K,V> pollFirstEntry() {
2940 dl 1.46 return isDescending? removeHighest() : removeLowest();
2941 dl 1.1 }
2942    
2943     public Map.Entry<K,V> pollLastEntry() {
2944 dl 1.46 return isDescending? removeLowest() : removeHighest();
2945 dl 1.1 }
2946    
2947     /* ---------------- Submap Views -------------- */
2948    
2949 jsr166 1.51 public NavigableSet<K> keySet() {
2950 dl 1.46 KeySet<K> ks = keySetView;
2951     return (ks != null) ? ks : (keySetView = new KeySet(this));
2952 dl 1.1 }
2953    
2954 dl 1.46 public NavigableSet<K> navigableKeySet() {
2955     KeySet<K> ks = keySetView;
2956     return (ks != null) ? ks : (keySetView = new KeySet(this));
2957     }
2958 dl 1.45
2959 dl 1.46 public Collection<V> values() {
2960     Collection<V> vs = valuesView;
2961     return (vs != null) ? vs : (valuesView = new Values(this));
2962 dl 1.1 }
2963    
2964 dl 1.46 public Set<Map.Entry<K,V>> entrySet() {
2965     Set<Map.Entry<K,V>> es = entrySetView;
2966     return (es != null) ? es : (entrySetView = new EntrySet(this));
2967 dl 1.1 }
2968    
2969 dl 1.46 public NavigableSet<K> descendingKeySet() {
2970     return descendingMap().navigableKeySet();
2971 dl 1.1 }
2972    
2973 dl 1.46 Iterator<K> keyIterator() {
2974     return new SubMapKeyIterator();
2975 dl 1.1 }
2976    
2977 dl 1.46 Iterator<V> valueIterator() {
2978     return new SubMapValueIterator();
2979 dl 1.1 }
2980    
2981 dl 1.46 Iterator<Map.Entry<K,V>> entryIterator() {
2982     return new SubMapEntryIterator();
2983 dl 1.1 }
2984    
2985 dl 1.46 /**
2986     * Variant of main Iter class to traverse through submaps.
2987     */
2988     abstract class SubMapIter<T> implements Iterator<T> {
2989     /** the last node returned by next() */
2990     Node<K,V> last;
2991     /** the next node to return from next(); */
2992     Node<K,V> next;
2993     /** Cache of next value field to maintain weak consistency */
2994     Object nextValue;
2995    
2996 dl 1.47 SubMapIter() {
2997 dl 1.46 for (;;) {
2998     next = isDescending? hiNode() : loNode();
2999     if (next == null)
3000     break;
3001     nextValue = next.value;
3002     if (nextValue != null && nextValue != next) {
3003     if (!inBounds(next.key)) {
3004     next = null;
3005     nextValue = null;
3006     }
3007     break;
3008     }
3009     }
3010 dl 1.1 }
3011 dl 1.46
3012     public final boolean hasNext() {
3013     return next != null;
3014 dl 1.1 }
3015 dl 1.46
3016     final void advance() {
3017     if ((last = next) == null)
3018     throw new NoSuchElementException();
3019     if (isDescending)
3020     descend();
3021     else
3022     ascend();
3023 dl 1.1 }
3024 dl 1.46
3025     private void ascend() {
3026     for (;;) {
3027     next = next.next;
3028     if (next == null)
3029     break;
3030     nextValue = next.value;
3031     if (nextValue != null && nextValue != next) {
3032     if (tooHigh(next.key)) {
3033     next = null;
3034     nextValue = null;
3035     }
3036     break;
3037     }
3038     }
3039     }
3040    
3041     private void descend() {
3042     for (;;) {
3043     next = m.findNear(last.key, LT);
3044     if (next == null)
3045     break;
3046     nextValue = next.value;
3047     if (nextValue != null && nextValue != next) {
3048     if (tooLow(next.key)) {
3049     next = null;
3050     nextValue = null;
3051     }
3052     break;
3053     }
3054     }
3055 dl 1.1 }
3056 dl 1.46
3057     public void remove() {
3058     Node<K,V> l = last;
3059     if (l == null)
3060     throw new IllegalStateException();
3061     m.remove(l.key);
3062 dl 1.1 }
3063 dl 1.46
3064     }
3065    
3066     final class SubMapValueIterator extends SubMapIter<V> {
3067     public V next() {
3068     Object v = nextValue;
3069     advance();
3070     return (V)v;
3071 dl 1.45 }
3072 dl 1.1 }
3073    
3074 dl 1.46 final class SubMapKeyIterator extends SubMapIter<K> {
3075     public K next() {
3076     Node<K,V> n = next;
3077     advance();
3078     return n.key;
3079     }
3080 dl 1.1 }
3081    
3082 dl 1.46 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3083     public Map.Entry<K,V> next() {
3084     Node<K,V> n = next;
3085     V v = (V)nextValue;
3086     advance();
3087     return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3088 dl 1.1 }
3089     }
3090     }
3091     }