ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.46
Committed: Wed Apr 19 15:08:04 2006 UTC (18 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.45: +598 -797 lines
Log Message:
Updated Navigable interfaces ind implementations

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package java.util.concurrent;
8     import java.util.*;
9     import java.util.concurrent.atomic.*;
10    
11     /**
12 jsr166 1.22 * A scalable concurrent {@link ConcurrentNavigableMap} implementation.
13     * The map is sorted according to the {@linkplain Comparable natural
14     * ordering} of its keys, or by a {@link Comparator} provided at map
15     * creation time, depending on which constructor is used.
16 dl 1.1 *
17     * <p>This class implements a concurrent variant of <a
18     * href="http://www.cs.umd.edu/~pugh/">SkipLists</a> providing
19     * expected average <i>log(n)</i> time cost for the
20     * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and
21     * <tt>remove</tt> operations and their variants. Insertion, removal,
22     * update, and access operations safely execute concurrently by
23     * multiple threads. Iterators are <i>weakly consistent</i>, returning
24     * elements reflecting the state of the map at some point at or since
25     * the creation of the iterator. They do <em>not</em> throw {@link
26     * ConcurrentModificationException}, and may proceed concurrently with
27     * other operations. Ascending key ordered views and their iterators
28     * are faster than descending ones.
29     *
30     * <p>All <tt>Map.Entry</tt> pairs returned by methods in this class
31     * and its views represent snapshots of mappings at the time they were
32     * produced. They do <em>not</em> support the <tt>Entry.setValue</tt>
33     * method. (Note however that it is possible to change mappings in the
34     * associated map using <tt>put</tt>, <tt>putIfAbsent</tt>, or
35     * <tt>replace</tt>, depending on exactly which effect you need.)
36     *
37     * <p>Beware that, unlike in most collections, the <tt>size</tt>
38     * method is <em>not</em> a constant-time operation. Because of the
39     * asynchronous nature of these maps, determining the current number
40     * of elements requires a traversal of the elements. Additionally,
41     * the bulk operations <tt>putAll</tt>, <tt>equals</tt>, and
42     * <tt>clear</tt> are <em>not</em> guaranteed to be performed
43     * atomically. For example, an iterator operating concurrently with a
44     * <tt>putAll</tt> operation might view only some of the added
45     * elements.
46     *
47     * <p>This class and its views and iterators implement all of the
48     * <em>optional</em> methods of the {@link Map} and {@link Iterator}
49     * interfaces. Like most other concurrent collections, this class does
50 jsr166 1.22 * <em>not</em> permit the use of <tt>null</tt> keys or values because some
51     * null return values cannot be reliably distinguished from the absence of
52     * elements.
53 dl 1.1 *
54 jsr166 1.21 * <p>This class is a member of the
55     * <a href="{@docRoot}/../guide/collections/index.html">
56     * Java Collections Framework</a>.
57     *
58 dl 1.1 * @author Doug Lea
59     * @param <K> the type of keys maintained by this map
60 dl 1.9 * @param <V> the type of mapped values
61 jsr166 1.20 * @since 1.6
62 dl 1.1 */
63 dl 1.9 public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
64 dl 1.1 implements ConcurrentNavigableMap<K,V>,
65 dl 1.9 Cloneable,
66 dl 1.1 java.io.Serializable {
67     /*
68     * This class implements a tree-like two-dimensionally linked skip
69     * list in which the index levels are represented in separate
70     * nodes from the base nodes holding data. There are two reasons
71     * for taking this approach instead of the usual array-based
72     * structure: 1) Array based implementations seem to encounter
73     * more complexity and overhead 2) We can use cheaper algorithms
74     * for the heavily-traversed index lists than can be used for the
75     * base lists. Here's a picture of some of the basics for a
76     * possible list with 2 levels of index:
77     *
78     * Head nodes Index nodes
79 dl 1.9 * +-+ right +-+ +-+
80 dl 1.1 * |2|---------------->| |--------------------->| |->null
81 dl 1.9 * +-+ +-+ +-+
82 dl 1.1 * | down | |
83     * v v v
84 dl 1.9 * +-+ +-+ +-+ +-+ +-+ +-+
85 dl 1.1 * |1|----------->| |->| |------>| |----------->| |------>| |->null
86 dl 1.9 * +-+ +-+ +-+ +-+ +-+ +-+
87 dl 1.1 * v | | | | |
88     * Nodes next v v v v v
89 dl 1.9 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
90 dl 1.1 * | |->|A|->|B|->|C|->|D|->|E|->|F|->|G|->|H|->|I|->|J|->|K|->null
91 dl 1.9 * +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+ +-+
92 dl 1.1 *
93     * The base lists use a variant of the HM linked ordered set
94     * algorithm. See Tim Harris, "A pragmatic implementation of
95     * non-blocking linked lists"
96     * http://www.cl.cam.ac.uk/~tlh20/publications.html and Maged
97     * Michael "High Performance Dynamic Lock-Free Hash Tables and
98     * List-Based Sets"
99     * http://www.research.ibm.com/people/m/michael/pubs.htm. The
100     * basic idea in these lists is to mark the "next" pointers of
101     * deleted nodes when deleting to avoid conflicts with concurrent
102     * insertions, and when traversing to keep track of triples
103     * (predecessor, node, successor) in order to detect when and how
104     * to unlink these deleted nodes.
105     *
106     * Rather than using mark-bits to mark list deletions (which can
107     * be slow and space-intensive using AtomicMarkedReference), nodes
108     * use direct CAS'able next pointers. On deletion, instead of
109     * marking a pointer, they splice in another node that can be
110     * thought of as standing for a marked pointer (indicating this by
111     * using otherwise impossible field values). Using plain nodes
112     * acts roughly like "boxed" implementations of marked pointers,
113     * but uses new nodes only when nodes are deleted, not for every
114     * link. This requires less space and supports faster
115     * traversal. Even if marked references were better supported by
116     * JVMs, traversal using this technique might still be faster
117     * because any search need only read ahead one more node than
118     * otherwise required (to check for trailing marker) rather than
119     * unmasking mark bits or whatever on each read.
120     *
121     * This approach maintains the essential property needed in the HM
122     * algorithm of changing the next-pointer of a deleted node so
123     * that any other CAS of it will fail, but implements the idea by
124     * changing the pointer to point to a different node, not by
125     * marking it. While it would be possible to further squeeze
126     * space by defining marker nodes not to have key/value fields, it
127     * isn't worth the extra type-testing overhead. The deletion
128     * markers are rarely encountered during traversal and are
129     * normally quickly garbage collected. (Note that this technique
130     * would not work well in systems without garbage collection.)
131     *
132     * In addition to using deletion markers, the lists also use
133     * nullness of value fields to indicate deletion, in a style
134     * similar to typical lazy-deletion schemes. If a node's value is
135     * null, then it is considered logically deleted and ignored even
136     * though it is still reachable. This maintains proper control of
137     * concurrent replace vs delete operations -- an attempted replace
138     * must fail if a delete beat it by nulling field, and a delete
139     * must return the last non-null value held in the field. (Note:
140     * Null, rather than some special marker, is used for value fields
141     * here because it just so happens to mesh with the Map API
142     * requirement that method get returns null if there is no
143     * mapping, which allows nodes to remain concurrently readable
144     * even when deleted. Using any other marker value here would be
145     * messy at best.)
146     *
147     * Here's the sequence of events for a deletion of node n with
148     * predecessor b and successor f, initially:
149     *
150 dl 1.9 * +------+ +------+ +------+
151 dl 1.1 * ... | b |------>| n |----->| f | ...
152 dl 1.9 * +------+ +------+ +------+
153 dl 1.1 *
154     * 1. CAS n's value field from non-null to null.
155     * From this point on, no public operations encountering
156     * the node consider this mapping to exist. However, other
157     * ongoing insertions and deletions might still modify
158     * n's next pointer.
159     *
160     * 2. CAS n's next pointer to point to a new marker node.
161     * From this point on, no other nodes can be appended to n.
162     * which avoids deletion errors in CAS-based linked lists.
163     *
164     * +------+ +------+ +------+ +------+
165     * ... | b |------>| n |----->|marker|------>| f | ...
166 dl 1.9 * +------+ +------+ +------+ +------+
167 dl 1.1 *
168     * 3. CAS b's next pointer over both n and its marker.
169     * From this point on, no new traversals will encounter n,
170     * and it can eventually be GCed.
171     * +------+ +------+
172     * ... | b |----------------------------------->| f | ...
173 dl 1.9 * +------+ +------+
174     *
175 dl 1.1 * A failure at step 1 leads to simple retry due to a lost race
176     * with another operation. Steps 2-3 can fail because some other
177     * thread noticed during a traversal a node with null value and
178     * helped out by marking and/or unlinking. This helping-out
179     * ensures that no thread can become stuck waiting for progress of
180     * the deleting thread. The use of marker nodes slightly
181     * complicates helping-out code because traversals must track
182     * consistent reads of up to four nodes (b, n, marker, f), not
183     * just (b, n, f), although the next field of a marker is
184     * immutable, and once a next field is CAS'ed to point to a
185     * marker, it never again changes, so this requires less care.
186     *
187     * Skip lists add indexing to this scheme, so that the base-level
188     * traversals start close to the locations being found, inserted
189     * or deleted -- usually base level traversals only traverse a few
190     * nodes. This doesn't change the basic algorithm except for the
191     * need to make sure base traversals start at predecessors (here,
192     * b) that are not (structurally) deleted, otherwise retrying
193 dl 1.9 * after processing the deletion.
194 dl 1.1 *
195     * Index levels are maintained as lists with volatile next fields,
196     * using CAS to link and unlink. Races are allowed in index-list
197     * operations that can (rarely) fail to link in a new index node
198     * or delete one. (We can't do this of course for data nodes.)
199     * However, even when this happens, the index lists remain sorted,
200     * so correctly serve as indices. This can impact performance,
201     * but since skip lists are probabilistic anyway, the net result
202     * is that under contention, the effective "p" value may be lower
203     * than its nominal value. And race windows are kept small enough
204     * that in practice these failures are rare, even under a lot of
205     * contention.
206     *
207     * The fact that retries (for both base and index lists) are
208     * relatively cheap due to indexing allows some minor
209     * simplifications of retry logic. Traversal restarts are
210     * performed after most "helping-out" CASes. This isn't always
211     * strictly necessary, but the implicit backoffs tend to help
212     * reduce other downstream failed CAS's enough to outweigh restart
213     * cost. This worsens the worst case, but seems to improve even
214     * highly contended cases.
215     *
216     * Unlike most skip-list implementations, index insertion and
217     * deletion here require a separate traversal pass occuring after
218     * the base-level action, to add or remove index nodes. This adds
219     * to single-threaded overhead, but improves contended
220     * multithreaded performance by narrowing interference windows,
221     * and allows deletion to ensure that all index nodes will be made
222     * unreachable upon return from a public remove operation, thus
223     * avoiding unwanted garbage retention. This is more important
224     * here than in some other data structures because we cannot null
225     * out node fields referencing user keys since they might still be
226     * read by other ongoing traversals.
227     *
228     * Indexing uses skip list parameters that maintain good search
229     * performance while using sparser-than-usual indices: The
230     * hardwired parameters k=1, p=0.5 (see method randomLevel) mean
231     * that about one-quarter of the nodes have indices. Of those that
232     * do, half have one level, a quarter have two, and so on (see
233     * Pugh's Skip List Cookbook, sec 3.4). The expected total space
234     * requirement for a map is slightly less than for the current
235     * implementation of java.util.TreeMap.
236     *
237     * Changing the level of the index (i.e, the height of the
238     * tree-like structure) also uses CAS. The head index has initial
239     * level/height of one. Creation of an index with height greater
240     * than the current level adds a level to the head index by
241     * CAS'ing on a new top-most head. To maintain good performance
242     * after a lot of removals, deletion methods heuristically try to
243     * reduce the height if the topmost levels appear to be empty.
244     * This may encounter races in which it possible (but rare) to
245     * reduce and "lose" a level just as it is about to contain an
246     * index (that will then never be encountered). This does no
247     * structural harm, and in practice appears to be a better option
248     * than allowing unrestrained growth of levels.
249     *
250     * The code for all this is more verbose than you'd like. Most
251     * operations entail locating an element (or position to insert an
252     * element). The code to do this can't be nicely factored out
253     * because subsequent uses require a snapshot of predecessor
254     * and/or successor and/or value fields which can't be returned
255     * all at once, at least not without creating yet another object
256     * to hold them -- creating such little objects is an especially
257     * bad idea for basic internal search operations because it adds
258     * to GC overhead. (This is one of the few times I've wished Java
259     * had macros.) Instead, some traversal code is interleaved within
260     * insertion and removal operations. The control logic to handle
261     * all the retry conditions is sometimes twisty. Most search is
262     * broken into 2 parts. findPredecessor() searches index nodes
263     * only, returning a base-level predecessor of the key. findNode()
264     * finishes out the base-level search. Even with this factoring,
265     * there is a fair amount of near-duplication of code to handle
266     * variants.
267     *
268     * For explanation of algorithms sharing at least a couple of
269     * features with this one, see Mikhail Fomitchev's thesis
270     * (http://www.cs.yorku.ca/~mikhail/), Keir Fraser's thesis
271 dl 1.4 * (http://www.cl.cam.ac.uk/users/kaf24/), and Hakan Sundell's
272 dl 1.1 * thesis (http://www.cs.chalmers.se/~phs/).
273     *
274     * Given the use of tree-like index nodes, you might wonder why
275     * this doesn't use some kind of search tree instead, which would
276     * support somewhat faster search operations. The reason is that
277     * there are no known efficient lock-free insertion and deletion
278     * algorithms for search trees. The immutability of the "down"
279     * links of index nodes (as opposed to mutable "left" fields in
280     * true trees) makes this tractable using only CAS operations.
281     *
282     * Notation guide for local variables
283     * Node: b, n, f for predecessor, node, successor
284     * Index: q, r, d for index node, right, down.
285     * t for another index node
286     * Head: h
287     * Levels: j
288     * Keys: k, key
289     * Values: v, value
290     * Comparisons: c
291     */
292    
293     private static final long serialVersionUID = -8627078645895051609L;
294    
295     /**
296 dl 1.40 * Generates the initial random seed for the cheaper per-instance
297     * random number generators used in randomLevel.
298     */
299     private static final Random seedGenerator = new Random();
300    
301     /**
302 dl 1.1 * Special value used to identify base-level header
303 dl 1.9 */
304 dl 1.1 private static final Object BASE_HEADER = new Object();
305    
306     /**
307 dl 1.9 * The topmost head index of the skiplist.
308 dl 1.1 */
309     private transient volatile HeadIndex<K,V> head;
310    
311     /**
312 jsr166 1.10 * The comparator used to maintain order in this map, or null
313 jsr166 1.22 * if using natural ordering.
314 dl 1.1 * @serial
315     */
316     private final Comparator<? super K> comparator;
317    
318     /**
319     * Seed for simple random number generator. Not volatile since it
320     * doesn't matter too much if different threads don't see updates.
321     */
322     private transient int randomSeed;
323    
324     /** Lazily initialized key set */
325     private transient KeySet keySet;
326     /** Lazily initialized entry set */
327     private transient EntrySet entrySet;
328     /** Lazily initialized values collection */
329     private transient Values values;
330     /** Lazily initialized descending key set */
331 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     * cast key as Comparator, which may cause ClassCastException,
612     * which is propagated back to caller.
613     */
614 dl 1.9 private Comparable<? super K> comparable(Object key) throws ClassCastException {
615     if (key == null)
616 dl 1.1 throw new NullPointerException();
617 dl 1.24 if (comparator != null)
618     return new ComparableUsingComparator<K>((K)key, comparator);
619     else
620     return (Comparable<? super K>)key;
621 dl 1.1 }
622    
623     /**
624 jsr166 1.10 * Compares using comparator or natural ordering. Used when the
625 dl 1.1 * ComparableUsingComparator approach doesn't apply.
626     */
627     int compare(K k1, K k2) throws ClassCastException {
628     Comparator<? super K> cmp = comparator;
629     if (cmp != null)
630     return cmp.compare(k1, k2);
631     else
632 jsr166 1.18 return ((Comparable<? super K>)k1).compareTo(k2);
633 dl 1.1 }
634    
635     /**
636 jsr166 1.10 * Returns true if given key greater than or equal to least and
637 dl 1.1 * strictly less than fence, bypassing either test if least or
638 dl 1.5 * fence are null. Needed mainly in submap operations.
639 dl 1.1 */
640     boolean inHalfOpenRange(K key, K least, K fence) {
641 dl 1.9 if (key == null)
642 dl 1.1 throw new NullPointerException();
643     return ((least == null || compare(key, least) >= 0) &&
644     (fence == null || compare(key, fence) < 0));
645     }
646    
647     /**
648 jsr166 1.10 * Returns true if given key greater than or equal to least and less
649 dl 1.1 * or equal to fence. Needed mainly in submap operations.
650     */
651     boolean inOpenRange(K key, K least, K fence) {
652 dl 1.9 if (key == null)
653 dl 1.1 throw new NullPointerException();
654     return ((least == null || compare(key, least) >= 0) &&
655     (fence == null || compare(key, fence) <= 0));
656     }
657    
658     /* ---------------- Traversal -------------- */
659    
660     /**
661 jsr166 1.10 * Returns a base-level node with key strictly less than given key,
662 dl 1.1 * or the base-level header if there is no such node. Also
663     * unlinks indexes to deleted nodes found along the way. Callers
664     * rely on this side-effect of clearing indices to deleted nodes.
665     * @param key the key
666 dl 1.9 * @return a predecessor of key
667 dl 1.1 */
668 dl 1.9 private Node<K,V> findPredecessor(Comparable<? super K> key) {
669 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.22 * Returns a {@link Set} view of the keys contained in this map.
1748     * 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     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1753     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1754     * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
1755     * operations.
1756     *
1757     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1758     * 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.22 * @return a set view of the keys contained in this map, sorted in
1764     * ascending order
1765 dl 1.1 */
1766     public Set<K> keySet() {
1767     KeySet ks = keySet;
1768 dl 1.46 return (ks != null) ? ks : (keySet = new KeySet(this));
1769 dl 1.1 }
1770    
1771     /**
1772 dl 1.46 * Returns a {@link NavigableSet} view of the keys contained in this map.
1773     * The set's iterator returns the keys in ascending order.
1774 jsr166 1.22 * The set is backed by the map, so changes to the map are
1775     * reflected in the set, and vice-versa. The set supports element
1776     * removal, which removes the corresponding mapping from the map,
1777     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1778     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
1779     * operations. It does not support the <tt>add</tt> or <tt>addAll</tt>
1780     * operations.
1781     *
1782     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1783     * that will never throw {@link ConcurrentModificationException},
1784 dl 1.1 * and guarantees to traverse elements as they existed upon
1785 jsr166 1.22 * construction of the iterator, and may (but is not guaranteed to)
1786     * reflect any modifications subsequent to construction.
1787 dl 1.46 *
1788     * @return a set view of the keys contained in this map, sorted in
1789     * ascending order
1790 dl 1.1 */
1791 dl 1.46 public NavigableSet<K> navigableKeySet() {
1792     KeySet ks = keySet;
1793     return (ks != null) ? ks : (keySet = new KeySet(this));
1794 dl 1.1 }
1795    
1796     /**
1797 jsr166 1.22 * Returns a {@link Collection} view of the values contained in this map.
1798     * The collection's iterator returns the values in ascending order
1799     * of the corresponding keys.
1800 dl 1.1 * The collection is backed by the map, so changes to the map are
1801     * reflected in the collection, and vice-versa. The collection
1802     * supports element removal, which removes the corresponding
1803 jsr166 1.22 * mapping from the map, via the <tt>Iterator.remove</tt>,
1804 dl 1.1 * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
1805 jsr166 1.22 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not
1806     * support the <tt>add</tt> or <tt>addAll</tt> operations.
1807 dl 1.1 *
1808 jsr166 1.22 * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1809     * that will never throw {@link ConcurrentModificationException},
1810     * and guarantees to traverse elements as they existed upon
1811     * construction of the iterator, and may (but is not guaranteed to)
1812     * reflect any modifications subsequent to construction.
1813 dl 1.1 */
1814     public Collection<V> values() {
1815     Values vs = values;
1816 dl 1.46 return (vs != null) ? vs : (values = new Values(this));
1817 dl 1.1 }
1818    
1819     /**
1820 jsr166 1.22 * Returns a {@link Set} view of the mappings contained in this map.
1821     * The set's iterator returns the entries in ascending key order.
1822     * The set is backed by the map, so changes to the map are
1823     * reflected in the set, and vice-versa. The set supports element
1824     * removal, which removes the corresponding mapping from the map,
1825     * via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
1826     * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt>
1827 dl 1.1 * operations. It does not support the <tt>add</tt> or
1828 jsr166 1.22 * <tt>addAll</tt> operations.
1829     *
1830     * <p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
1831     * that will never throw {@link ConcurrentModificationException},
1832     * and guarantees to traverse elements as they existed upon
1833     * construction of the iterator, and may (but is not guaranteed to)
1834     * reflect any modifications subsequent to construction.
1835     *
1836     * <p>The <tt>Map.Entry</tt> elements returned by
1837 dl 1.1 * <tt>iterator.next()</tt> do <em>not</em> support the
1838     * <tt>setValue</tt> operation.
1839     *
1840 jsr166 1.22 * @return a set view of the mappings contained in this map,
1841     * sorted in ascending key order
1842 dl 1.1 */
1843     public Set<Map.Entry<K,V>> entrySet() {
1844     EntrySet es = entrySet;
1845 dl 1.46 return (es != null) ? es : (entrySet = new EntrySet(this));
1846     }
1847    
1848     public ConcurrentNavigableMap<K,V> descendingMap() {
1849     ConcurrentNavigableMap<K,V> dm = descendingMap;
1850     return (dm != null) ? dm : (descendingMap = new SubMap<K,V>
1851     (this, null, false, null, false, true));
1852 dl 1.1 }
1853    
1854 dl 1.46 public NavigableSet<K> descendingKeySet() {
1855     return descendingMap().navigableKeySet();
1856 dl 1.1 }
1857    
1858     /* ---------------- AbstractMap Overrides -------------- */
1859    
1860     /**
1861     * Compares the specified object with this map for equality.
1862     * Returns <tt>true</tt> if the given object is also a map and the
1863     * two maps represent the same mappings. More formally, two maps
1864 jsr166 1.22 * <tt>m1</tt> and <tt>m2</tt> represent the same mappings if
1865 jsr166 1.39 * <tt>m1.entrySet().equals(m2.entrySet())</tt>. This
1866 dl 1.1 * operation may return misleading results if either map is
1867     * concurrently modified during execution of this method.
1868     *
1869 jsr166 1.22 * @param o object to be compared for equality with this map
1870     * @return <tt>true</tt> if the specified object is equal to this map
1871 dl 1.1 */
1872     public boolean equals(Object o) {
1873     if (o == this)
1874     return true;
1875     if (!(o instanceof Map))
1876     return false;
1877 dl 1.25 Map<?,?> m = (Map<?,?>) o;
1878 dl 1.1 try {
1879 dl 1.25 for (Map.Entry<K,V> e : this.entrySet())
1880     if (! e.getValue().equals(m.get(e.getKey())))
1881     return false;
1882     for (Map.Entry<?,?> e : m.entrySet()) {
1883     Object k = e.getKey();
1884     Object v = e.getValue();
1885     if (k == null || v == null || !v.equals(get(k)))
1886     return false;
1887     }
1888     return true;
1889 jsr166 1.15 } catch (ClassCastException unused) {
1890 dl 1.1 return false;
1891 jsr166 1.15 } catch (NullPointerException unused) {
1892 dl 1.1 return false;
1893     }
1894     }
1895    
1896     /* ------ ConcurrentMap API methods ------ */
1897    
1898     /**
1899 jsr166 1.22 * {@inheritDoc}
1900     *
1901     * @return the previous value associated with the specified key,
1902     * or <tt>null</tt> if there was no mapping for the key
1903     * @throws ClassCastException if the specified key cannot be compared
1904     * with the keys currently in the map
1905     * @throws NullPointerException if the specified key or value is null
1906 dl 1.1 */
1907     public V putIfAbsent(K key, V value) {
1908 dl 1.9 if (value == null)
1909 dl 1.1 throw new NullPointerException();
1910     return doPut(key, value, true);
1911     }
1912    
1913     /**
1914 jsr166 1.22 * {@inheritDoc}
1915     *
1916     * @throws ClassCastException if the specified key cannot be compared
1917     * with the keys currently in the map
1918 dl 1.23 * @throws NullPointerException if the specified key is null
1919 dl 1.1 */
1920     public boolean remove(Object key, Object value) {
1921 dl 1.45 if (key == null)
1922     throw new NullPointerException();
1923 dl 1.9 if (value == null)
1924 dl 1.23 return false;
1925 dl 1.1 return doRemove(key, value) != null;
1926     }
1927    
1928     /**
1929 jsr166 1.22 * {@inheritDoc}
1930     *
1931     * @throws ClassCastException if the specified key cannot be compared
1932     * with the keys currently in the map
1933     * @throws NullPointerException if any of the arguments are null
1934 dl 1.1 */
1935     public boolean replace(K key, V oldValue, V newValue) {
1936 dl 1.9 if (oldValue == null || newValue == null)
1937 dl 1.1 throw new NullPointerException();
1938 dl 1.9 Comparable<? super K> k = comparable(key);
1939 dl 1.1 for (;;) {
1940     Node<K,V> n = findNode(k);
1941     if (n == null)
1942     return false;
1943     Object v = n.value;
1944     if (v != null) {
1945     if (!oldValue.equals(v))
1946     return false;
1947     if (n.casValue(v, newValue))
1948     return true;
1949     }
1950     }
1951     }
1952    
1953     /**
1954 jsr166 1.22 * {@inheritDoc}
1955     *
1956     * @return the previous value associated with the specified key,
1957     * or <tt>null</tt> if there was no mapping for the key
1958     * @throws ClassCastException if the specified key cannot be compared
1959     * with the keys currently in the map
1960     * @throws NullPointerException if the specified key or value is null
1961 dl 1.1 */
1962     public V replace(K key, V value) {
1963 dl 1.9 if (value == null)
1964 dl 1.1 throw new NullPointerException();
1965 dl 1.9 Comparable<? super K> k = comparable(key);
1966 dl 1.1 for (;;) {
1967     Node<K,V> n = findNode(k);
1968     if (n == null)
1969     return null;
1970     Object v = n.value;
1971     if (v != null && n.casValue(v, value))
1972     return (V)v;
1973     }
1974     }
1975    
1976     /* ------ SortedMap API methods ------ */
1977    
1978     public Comparator<? super K> comparator() {
1979     return comparator;
1980     }
1981    
1982     /**
1983 jsr166 1.22 * @throws NoSuchElementException {@inheritDoc}
1984 dl 1.1 */
1985 dl 1.9 public K firstKey() {
1986 dl 1.1 Node<K,V> n = findFirst();
1987     if (n == null)
1988     throw new NoSuchElementException();
1989     return n.key;
1990     }
1991    
1992     /**
1993 jsr166 1.22 * @throws NoSuchElementException {@inheritDoc}
1994 dl 1.1 */
1995     public K lastKey() {
1996     Node<K,V> n = findLast();
1997     if (n == null)
1998     throw new NoSuchElementException();
1999     return n.key;
2000     }
2001    
2002     /**
2003 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2004     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is null
2005     * @throws IllegalArgumentException {@inheritDoc}
2006 dl 1.1 */
2007 dl 1.46 public ConcurrentNavigableMap<K,V> navigableSubMap(K fromKey,
2008     boolean fromInclusive,
2009     K toKey,
2010     boolean toInclusive) {
2011 dl 1.1 if (fromKey == null || toKey == null)
2012     throw new NullPointerException();
2013 dl 1.46 return new SubMap<K,V>
2014     (this, fromKey, fromInclusive, toKey, toInclusive, false);
2015 dl 1.1 }
2016    
2017     /**
2018 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2019     * @throws NullPointerException if <tt>toKey</tt> is null
2020     * @throws IllegalArgumentException {@inheritDoc}
2021 dl 1.1 */
2022 dl 1.46 public ConcurrentNavigableMap<K,V> navigableHeadMap(K toKey,
2023     boolean inclusive) {
2024 dl 1.1 if (toKey == null)
2025     throw new NullPointerException();
2026 dl 1.46 return new SubMap<K,V>
2027     (this, null, false, toKey, inclusive, false);
2028 dl 1.1 }
2029    
2030     /**
2031 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2032     * @throws NullPointerException if <tt>fromKey</tt> is null
2033     * @throws IllegalArgumentException {@inheritDoc}
2034 dl 1.1 */
2035 dl 1.46 public ConcurrentNavigableMap<K,V> navigableTailMap(K fromKey,
2036     boolean inclusive) {
2037 dl 1.6 if (fromKey == null)
2038     throw new NullPointerException();
2039 dl 1.46 return new SubMap<K,V>
2040     (this, fromKey, inclusive, null, false, false);
2041 dl 1.6 }
2042    
2043     /**
2044 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2045     * @throws NullPointerException if <tt>fromKey</tt> or <tt>toKey</tt> is null
2046     * @throws IllegalArgumentException {@inheritDoc}
2047 dl 1.6 */
2048 dl 1.37 public ConcurrentNavigableMap<K,V> subMap(K fromKey, K toKey) {
2049 dl 1.46 return navigableSubMap(fromKey, true, toKey, false);
2050 dl 1.6 }
2051    
2052     /**
2053 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2054     * @throws NullPointerException if <tt>toKey</tt> is null
2055     * @throws IllegalArgumentException {@inheritDoc}
2056 dl 1.6 */
2057 dl 1.37 public ConcurrentNavigableMap<K,V> headMap(K toKey) {
2058 dl 1.46 return navigableHeadMap(toKey, false);
2059 dl 1.6 }
2060    
2061     /**
2062 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2063     * @throws NullPointerException if <tt>fromKey</tt> is null
2064     * @throws IllegalArgumentException {@inheritDoc}
2065 dl 1.6 */
2066 dl 1.37 public ConcurrentNavigableMap<K,V> tailMap(K fromKey) {
2067 dl 1.46 return navigableTailMap(fromKey, true);
2068 dl 1.1 }
2069    
2070     /* ---------------- Relational operations -------------- */
2071    
2072     /**
2073 jsr166 1.22 * Returns a key-value mapping associated with the greatest key
2074     * strictly less than the given key, or <tt>null</tt> if there is
2075     * no such key. The returned entry does <em>not</em> support the
2076     * <tt>Entry.setValue</tt> method.
2077 dl 1.9 *
2078 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2079     * @throws NullPointerException if the specified key is null
2080 dl 1.1 */
2081 jsr166 1.22 public Map.Entry<K,V> lowerEntry(K key) {
2082     return getNear(key, LT);
2083 dl 1.1 }
2084    
2085     /**
2086 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2087     * @throws NullPointerException if the specified key is null
2088 dl 1.1 */
2089 jsr166 1.22 public K lowerKey(K key) {
2090     Node<K,V> n = findNear(key, LT);
2091 dl 1.1 return (n == null)? null : n.key;
2092     }
2093    
2094     /**
2095 jsr166 1.22 * Returns a key-value mapping associated with the greatest key
2096     * less than or equal to the given key, or <tt>null</tt> if there
2097     * is no such key. The returned entry does <em>not</em> support
2098 dl 1.1 * the <tt>Entry.setValue</tt> method.
2099 dl 1.9 *
2100 jsr166 1.22 * @param key the key
2101     * @throws ClassCastException {@inheritDoc}
2102     * @throws NullPointerException if the specified key is null
2103 dl 1.1 */
2104 jsr166 1.22 public Map.Entry<K,V> floorEntry(K key) {
2105     return getNear(key, LT|EQ);
2106 dl 1.1 }
2107    
2108     /**
2109 jsr166 1.22 * @param key the key
2110     * @throws ClassCastException {@inheritDoc}
2111     * @throws NullPointerException if the specified key is null
2112 dl 1.1 */
2113 jsr166 1.22 public K floorKey(K key) {
2114     Node<K,V> n = findNear(key, LT|EQ);
2115 dl 1.1 return (n == null)? null : n.key;
2116     }
2117    
2118     /**
2119 jsr166 1.22 * Returns a key-value mapping associated with the least key
2120     * greater than or equal to the given key, or <tt>null</tt> if
2121     * there is no such entry. The returned entry does <em>not</em>
2122     * support the <tt>Entry.setValue</tt> method.
2123 dl 1.9 *
2124 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2125     * @throws NullPointerException if the specified key is null
2126 dl 1.1 */
2127 jsr166 1.22 public Map.Entry<K,V> ceilingEntry(K key) {
2128     return getNear(key, GT|EQ);
2129 dl 1.1 }
2130    
2131     /**
2132 jsr166 1.22 * @throws ClassCastException {@inheritDoc}
2133     * @throws NullPointerException if the specified key is null
2134 dl 1.1 */
2135 jsr166 1.22 public K ceilingKey(K key) {
2136     Node<K,V> n = findNear(key, GT|EQ);
2137 dl 1.1 return (n == null)? null : n.key;
2138     }
2139    
2140     /**
2141     * Returns a key-value mapping associated with the least key
2142     * strictly greater than the given key, or <tt>null</tt> if there
2143 jsr166 1.22 * is no such key. The returned entry does <em>not</em> support
2144 dl 1.1 * the <tt>Entry.setValue</tt> method.
2145 dl 1.9 *
2146 jsr166 1.22 * @param key the key
2147     * @throws ClassCastException {@inheritDoc}
2148     * @throws NullPointerException if the specified key is null
2149 dl 1.1 */
2150     public Map.Entry<K,V> higherEntry(K key) {
2151     return getNear(key, GT);
2152     }
2153    
2154     /**
2155 jsr166 1.22 * @param key the key
2156     * @throws ClassCastException {@inheritDoc}
2157     * @throws NullPointerException if the specified key is null
2158 dl 1.1 */
2159     public K higherKey(K key) {
2160     Node<K,V> n = findNear(key, GT);
2161     return (n == null)? null : n.key;
2162     }
2163    
2164     /**
2165     * Returns a key-value mapping associated with the least
2166     * key in this map, or <tt>null</tt> if the map is empty.
2167     * The returned entry does <em>not</em> support
2168     * the <tt>Entry.setValue</tt> method.
2169     */
2170     public Map.Entry<K,V> firstEntry() {
2171     for (;;) {
2172     Node<K,V> n = findFirst();
2173 dl 1.9 if (n == null)
2174 dl 1.1 return null;
2175 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2176 dl 1.1 if (e != null)
2177     return e;
2178     }
2179     }
2180    
2181     /**
2182     * Returns a key-value mapping associated with the greatest
2183     * key in this map, or <tt>null</tt> if the map is empty.
2184     * The returned entry does <em>not</em> support
2185     * the <tt>Entry.setValue</tt> method.
2186     */
2187     public Map.Entry<K,V> lastEntry() {
2188     for (;;) {
2189     Node<K,V> n = findLast();
2190 dl 1.9 if (n == null)
2191 dl 1.1 return null;
2192 dl 1.2 AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
2193 dl 1.1 if (e != null)
2194     return e;
2195     }
2196     }
2197    
2198     /**
2199     * Removes and returns a key-value mapping associated with
2200     * the least key in this map, or <tt>null</tt> if the map is empty.
2201     * The returned entry does <em>not</em> support
2202     * the <tt>Entry.setValue</tt> method.
2203     */
2204     public Map.Entry<K,V> pollFirstEntry() {
2205 dl 1.25 return doRemoveFirstEntry();
2206 dl 1.1 }
2207    
2208     /**
2209     * Removes and returns a key-value mapping associated with
2210     * the greatest key in this map, or <tt>null</tt> if the map is empty.
2211     * The returned entry does <em>not</em> support
2212     * the <tt>Entry.setValue</tt> method.
2213     */
2214     public Map.Entry<K,V> pollLastEntry() {
2215 dl 1.31 return doRemoveLastEntry();
2216 dl 1.1 }
2217    
2218    
2219     /* ---------------- Iterators -------------- */
2220    
2221     /**
2222 dl 1.46 * Base of iterator classes:
2223 dl 1.1 */
2224 dl 1.46 abstract class Iter<T> implements Iterator<T> {
2225 dl 1.1 /** the last node returned by next() */
2226     Node<K,V> last;
2227     /** the next node to return from next(); */
2228     Node<K,V> next;
2229     /** Cache of next value field to maintain weak consistency */
2230     Object nextValue;
2231    
2232 jsr166 1.13 /** Initializes ascending iterator for entire range. */
2233 dl 1.46 Iter() {
2234 dl 1.1 for (;;) {
2235     next = findFirst();
2236     if (next == null)
2237     break;
2238     nextValue = next.value;
2239     if (nextValue != null && nextValue != next)
2240     break;
2241     }
2242     }
2243    
2244 dl 1.46 public final boolean hasNext() {
2245     return next != null;
2246 dl 1.1 }
2247 dl 1.46
2248 jsr166 1.13 /** Advances next to higher entry. */
2249 dl 1.46 final void advance() {
2250 dl 1.1 if ((last = next) == null)
2251     throw new NoSuchElementException();
2252     for (;;) {
2253     next = next.next;
2254     if (next == null)
2255     break;
2256     nextValue = next.value;
2257     if (nextValue != null && nextValue != next)
2258     break;
2259     }
2260     }
2261    
2262     public void remove() {
2263     Node<K,V> l = last;
2264     if (l == null)
2265     throw new IllegalStateException();
2266     // It would not be worth all of the overhead to directly
2267     // unlink from here. Using remove is fast enough.
2268     ConcurrentSkipListMap.this.remove(l.key);
2269     }
2270    
2271     }
2272    
2273 dl 1.46 final class ValueIterator extends Iter<V> {
2274 dl 1.9 public V next() {
2275 dl 1.1 Object v = nextValue;
2276 dl 1.46 advance();
2277 dl 1.1 return (V)v;
2278     }
2279     }
2280    
2281 dl 1.46 final class KeyIterator extends Iter<K> {
2282 dl 1.9 public K next() {
2283 dl 1.1 Node<K,V> n = next;
2284 dl 1.46 advance();
2285 dl 1.1 return n.key;
2286     }
2287     }
2288    
2289 dl 1.46 final class EntryIterator extends Iter<Map.Entry<K,V>> {
2290     public Map.Entry<K,V> next() {
2291     Node<K,V> n = next;
2292     V v = (V)nextValue;
2293     advance();
2294     return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
2295 dl 1.1 }
2296 dl 1.46 }
2297 dl 1.1
2298 dl 1.46 // Factory methods for iterators needed by ConcurrentSkipListSet etc
2299    
2300     Iterator<K> keyIterator() {
2301 dl 1.1 return new KeyIterator();
2302     }
2303    
2304 dl 1.46 Iterator<V> valueIterator() {
2305     return new ValueIterator();
2306 dl 1.1 }
2307    
2308 dl 1.46 Iterator<Map.Entry<K,V>> entryIterator() {
2309     return new EntryIterator();
2310 dl 1.1 }
2311    
2312 dl 1.46 /* ---------------- View Classes -------------- */
2313    
2314     /*
2315     * View classes are static, delegating to a ConcurrentNavigableMap
2316     * to allow use by SubMaps, which outweighs the ugliness of
2317     * needing type-tests for Iterator methods.
2318     */
2319    
2320     static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
2321     private final ConcurrentNavigableMap<E,Object> m;
2322     KeySet(ConcurrentNavigableMap<E,Object> map) { m = map; }
2323     public int size() { return m.size(); }
2324     public boolean isEmpty() { return m.isEmpty(); }
2325     public boolean contains(Object o) { return m.containsKey(o); }
2326     public boolean remove(Object o) { return m.remove(o) != null; }
2327     public void clear() { m.clear(); }
2328     public E lower(E e) { return m.lowerKey(e); }
2329     public E floor(E e) { return m.floorKey(e); }
2330     public E ceiling(E e) { return m.ceilingKey(e); }
2331     public E higher(E e) { return m.higherKey(e); }
2332     public Comparator<? super E> comparator() { return m.comparator(); }
2333     public E first() { return m.firstKey(); }
2334     public E last() { return m.lastKey(); }
2335     public E pollFirst() {
2336     Map.Entry<E,Object> e = m.pollFirstEntry();
2337     return e == null? null : e.getKey();
2338     }
2339     public E pollLast() {
2340     Map.Entry<E,Object> e = m.pollLastEntry();
2341     return e == null? null : e.getKey();
2342     }
2343     public Iterator<E> iterator() {
2344     if (m instanceof ConcurrentSkipListMap)
2345     return ((ConcurrentSkipListMap<E,Object>)m).keyIterator();
2346     else
2347     return ((ConcurrentSkipListMap.SubMap<E,Object>)m).keyIterator();
2348 dl 1.1 }
2349 dl 1.45 public boolean equals(Object o) {
2350     if (o == this)
2351     return true;
2352     if (!(o instanceof Set))
2353     return false;
2354     Collection<?> c = (Collection<?>) o;
2355     try {
2356     return containsAll(c) && c.containsAll(this);
2357     } catch (ClassCastException unused) {
2358     return false;
2359     } catch (NullPointerException unused) {
2360     return false;
2361     }
2362     }
2363 dl 1.46 public Iterator<E> descendingIterator() {
2364     return descendingSet().iterator();
2365     }
2366     public NavigableSet<E> navigableSubSet(E fromElement,
2367     boolean fromInclusive,
2368     E toElement,
2369     boolean toInclusive) {
2370     return new ConcurrentSkipListSet<E>
2371     (m.navigableSubMap(fromElement, fromInclusive,
2372     toElement, toInclusive));
2373     }
2374     public NavigableSet<E> navigableHeadSet(E toElement, boolean inclusive) {
2375     return new ConcurrentSkipListSet<E>(m.navigableHeadMap(toElement, inclusive));
2376     }
2377     public NavigableSet<E> navigableTailSet(E fromElement, boolean inclusive) {
2378     return new ConcurrentSkipListSet<E>(m.navigableTailMap(fromElement, inclusive));
2379     }
2380     public SortedSet<E> subSet(E fromElement, E toElement) {
2381     return navigableSubSet(fromElement, true, toElement, false);
2382     }
2383     public SortedSet<E> headSet(E toElement) {
2384     return navigableHeadSet(toElement, false);
2385     }
2386     public SortedSet<E> tailSet(E fromElement) {
2387     return navigableTailSet(fromElement, true);
2388     }
2389     public NavigableSet<E> descendingSet() {
2390     return new ConcurrentSkipListSet(m.descendingMap());
2391     }
2392 dl 1.1 }
2393    
2394 dl 1.46 static final class Values<E> extends AbstractCollection<E> {
2395     private final ConcurrentNavigableMap<Object, E> m;
2396     Values(ConcurrentNavigableMap<Object, E> map) {
2397     m = map;
2398 dl 1.1 }
2399 dl 1.46 public Iterator<E> iterator() {
2400     if (m instanceof ConcurrentSkipListMap)
2401     return ((ConcurrentSkipListMap<Object,E>)m).valueIterator();
2402     else
2403     return ((SubMap<Object,E>)m).valueIterator();
2404 dl 1.1 }
2405     public boolean isEmpty() {
2406 dl 1.46 return m.isEmpty();
2407 dl 1.1 }
2408     public int size() {
2409 dl 1.46 return m.size();
2410 dl 1.1 }
2411     public boolean contains(Object o) {
2412 dl 1.46 return m.containsValue(o);
2413 dl 1.1 }
2414     public void clear() {
2415 dl 1.46 m.clear();
2416 dl 1.1 }
2417     }
2418    
2419 dl 1.46 static final class EntrySet<K1,V1> extends AbstractSet<Map.Entry<K1,V1>> {
2420     private final ConcurrentNavigableMap<K1, V1> m;
2421     EntrySet(ConcurrentNavigableMap<K1, V1> map) {
2422     m = map;
2423 dl 1.1 }
2424 dl 1.46
2425     public Iterator<Map.Entry<K1,V1>> iterator() {
2426     if (m instanceof ConcurrentSkipListMap)
2427     return ((ConcurrentSkipListMap<K1,V1>)m).entryIterator();
2428     else
2429     return ((SubMap<K1,V1>)m).entryIterator();
2430     }
2431    
2432 dl 1.1 public boolean contains(Object o) {
2433     if (!(o instanceof Map.Entry))
2434     return false;
2435 dl 1.46 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2436     V1 v = m.get(e.getKey());
2437 dl 1.1 return v != null && v.equals(e.getValue());
2438     }
2439     public boolean remove(Object o) {
2440     if (!(o instanceof Map.Entry))
2441     return false;
2442 dl 1.46 Map.Entry<K1,V1> e = (Map.Entry<K1,V1>)o;
2443     return m.remove(e.getKey(),
2444 dl 1.1 e.getValue());
2445     }
2446     public boolean isEmpty() {
2447 dl 1.46 return m.isEmpty();
2448 dl 1.1 }
2449     public int size() {
2450 dl 1.46 return m.size();
2451 dl 1.1 }
2452     public void clear() {
2453 dl 1.46 m.clear();
2454 dl 1.1 }
2455 dl 1.45 public boolean equals(Object o) {
2456     if (o == this)
2457     return true;
2458     if (!(o instanceof Set))
2459     return false;
2460     Collection<?> c = (Collection<?>) o;
2461     try {
2462     return containsAll(c) && c.containsAll(this);
2463     } catch (ClassCastException unused) {
2464     return false;
2465     } catch (NullPointerException unused) {
2466     return false;
2467     }
2468     }
2469 dl 1.1 }
2470    
2471     /**
2472     * Submaps returned by {@link ConcurrentSkipListMap} submap operations
2473     * represent a subrange of mappings of their underlying
2474     * maps. Instances of this class support all methods of their
2475     * underlying maps, differing in that mappings outside their range are
2476     * ignored, and attempts to add mappings outside their ranges result
2477     * in {@link IllegalArgumentException}. Instances of this class are
2478     * constructed only using the <tt>subMap</tt>, <tt>headMap</tt>, and
2479     * <tt>tailMap</tt> methods of their underlying maps.
2480     */
2481 dl 1.46 static final class SubMap<K,V> extends AbstractMap<K,V>
2482     implements ConcurrentNavigableMap<K,V>, Cloneable,
2483     java.io.Serializable {
2484 dl 1.1 private static final long serialVersionUID = -7647078645895051609L;
2485    
2486     /** Underlying map */
2487     private final ConcurrentSkipListMap<K,V> m;
2488     /** lower bound key, or null if from start */
2489 dl 1.46 private final K lo;
2490     /** upper bound key, or null if to end */
2491     private final K hi;
2492     /** inclusion flag for lo */
2493     private final boolean loInclusive;
2494     /** inclusion flag for hi */
2495     private final boolean hiInclusive;
2496     /** direction */
2497     private final boolean isDescending;
2498    
2499 dl 1.1 // Lazily initialized view holders
2500 dl 1.46 private transient KeySet<K> keySetView;
2501 dl 1.1 private transient Set<Map.Entry<K,V>> entrySetView;
2502     private transient Collection<V> valuesView;
2503    
2504     /**
2505 dl 1.46 * Creates a new submap, initializing all fields
2506     */
2507     SubMap(ConcurrentSkipListMap<K,V> map,
2508     K fromKey, boolean fromInclusive,
2509     K toKey, boolean toInclusive,
2510     boolean isDescending) {
2511     if (fromKey != null && toKey != null &&
2512     map.compare(fromKey, toKey) > 0)
2513 dl 1.1 throw new IllegalArgumentException("inconsistent range");
2514     this.m = map;
2515 dl 1.46 this.lo = fromKey;
2516     this.hi = toKey;
2517     this.loInclusive = fromInclusive;
2518     this.hiInclusive = toInclusive;
2519     this.isDescending = isDescending;
2520 dl 1.1 }
2521    
2522     /* ---------------- Utilities -------------- */
2523    
2524 dl 1.46 private boolean tooLow(K key) {
2525     if (lo != null) {
2526     int c = m.compare(key, lo);
2527     if (c < 0 || (c == 0 && !loInclusive))
2528     return true;
2529     }
2530     return false;
2531 dl 1.1 }
2532    
2533 dl 1.46 private boolean tooHigh(K key) {
2534     if (hi != null) {
2535     int c = m.compare(key, hi);
2536     if (c > 0 || (c == 0 && !hiInclusive))
2537     return true;
2538     }
2539     return false;
2540 dl 1.1 }
2541    
2542 dl 1.46 private boolean inBounds(K key) {
2543     return !tooLow(key) && !tooHigh(key);
2544 dl 1.1 }
2545    
2546 dl 1.46 private void checkKeyBounds(K key) throws IllegalArgumentException {
2547     if (key == null)
2548     throw new NullPointerException();
2549     if (!inBounds(key))
2550     throw new IllegalArgumentException("key out of range");
2551 dl 1.1 }
2552    
2553 dl 1.46 /**
2554     * Returns true if node key is less than upper bound of range
2555     */
2556     private boolean isBeforeEnd(ConcurrentSkipListMap.Node<K,V> n) {
2557     if (n == null)
2558     return false;
2559     if (hi == null)
2560     return true;
2561     K k = n.key;
2562     if (k == null) // pass by markers and headers
2563     return true;
2564     int c = m.compare(k, hi);
2565     if (c > 0 || (c == 0 && !hiInclusive))
2566     return false;
2567     return true;
2568 dl 1.1 }
2569    
2570 dl 1.46 /**
2571     * Returns lowest node. This node might not be in range, so
2572     * most usages need to check bounds
2573     */
2574     private ConcurrentSkipListMap.Node<K,V> loNode() {
2575     if (lo == null)
2576     return m.findFirst();
2577     else if (loInclusive)
2578     return m.findNear(lo, m.GT|m.EQ);
2579     else
2580     return m.findNear(lo, m.GT);
2581 dl 1.1 }
2582    
2583     /**
2584 dl 1.46 * Returns highest node. This node might not be in range, so
2585     * most usages need to check bounds
2586 dl 1.1 */
2587 dl 1.46 private ConcurrentSkipListMap.Node<K,V> hiNode() {
2588     if (hi == null)
2589     return m.findLast();
2590     else if (hiInclusive)
2591     return m.findNear(hi, m.LT|m.EQ);
2592     else
2593     return m.findNear(hi, m.LT);
2594 dl 1.1 }
2595    
2596     /**
2597 dl 1.46 * Returns lowest absolute key (ignoring directonality)
2598 dl 1.1 */
2599 dl 1.46 private K lowestKey() {
2600     ConcurrentSkipListMap.Node<K,V> n = loNode();
2601     if (isBeforeEnd(n))
2602     return n.key;
2603     else
2604     throw new NoSuchElementException();
2605     }
2606    
2607     /**
2608     * Returns highest absolute key (ignoring directonality)
2609     */
2610     private K highestKey() {
2611     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2612     if (n != null) {
2613     K last = n.key;
2614     if (inBounds(last))
2615     return last;
2616     }
2617     throw new NoSuchElementException();
2618     }
2619    
2620     private Map.Entry<K,V> lowestEntry() {
2621     for (;;) {
2622     ConcurrentSkipListMap.Node<K,V> n = loNode();
2623     if (!isBeforeEnd(n))
2624     return null;
2625     Map.Entry<K,V> e = n.createSnapshot();
2626     if (e != null)
2627     return e;
2628     }
2629     }
2630    
2631     private Map.Entry<K,V> highestEntry() {
2632     for (;;) {
2633     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2634     if (n == null || !inBounds(n.key))
2635     return null;
2636     Map.Entry<K,V> e = n.createSnapshot();
2637     if (e != null)
2638     return e;
2639     }
2640     }
2641    
2642     private Map.Entry<K,V> removeLowest() {
2643     for (;;) {
2644     Node<K,V> n = loNode();
2645     if (n == null)
2646     return null;
2647     K k = n.key;
2648     if (!inBounds(k))
2649     return null;
2650     V v = m.doRemove(k, null);
2651     if (v != null)
2652     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2653     }
2654     }
2655    
2656     private Map.Entry<K,V> removeHighest() {
2657     for (;;) {
2658     Node<K,V> n = hiNode();
2659     if (n == null)
2660     return null;
2661     K k = n.key;
2662     if (!inBounds(k))
2663     return null;
2664     V v = m.doRemove(k, null);
2665     if (v != null)
2666     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2667     }
2668 dl 1.1 }
2669    
2670     /**
2671 dl 1.46 * Submap version of ConcurrentSkipListMap.getNearEntry
2672 dl 1.1 */
2673 dl 1.46 private Map.Entry<K,V> getNearEntry(K key, int rel) {
2674     if (isDescending) { // adjust relation for direction
2675     if ((rel & m.LT) == 0)
2676     rel |= m.LT;
2677     else
2678     rel &= ~m.LT;
2679     }
2680     if (tooLow(key))
2681     return ((rel & m.LT) != 0)? null : lowestEntry();
2682     if (tooHigh(key))
2683     return ((rel & m.LT) != 0)? highestEntry() : null;
2684     for (;;) {
2685     Node<K,V> n = m.findNear(key, rel);
2686     if (n == null || !inBounds(n.key))
2687     return null;
2688     K k = n.key;
2689     V v = n.getValidValue();
2690     if (v != null)
2691     return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
2692     }
2693 dl 1.1 }
2694    
2695 dl 1.46 // Almost the the same as getNearEntry, except for keys
2696     private K getNearKey(K key, int rel) {
2697     if (isDescending) { // adjust relation for direction
2698     if ((rel & m.LT) == 0)
2699     rel |= m.LT;
2700     else
2701     rel &= ~m.LT;
2702     }
2703     if (tooLow(key)) {
2704     if ((rel & m.LT) == 0) {
2705     ConcurrentSkipListMap.Node<K,V> n = loNode();
2706     if (isBeforeEnd(n))
2707     return n.key;
2708     }
2709     return null;
2710     }
2711     if (tooHigh(key)) {
2712     if ((rel & m.LT) != 0) {
2713     ConcurrentSkipListMap.Node<K,V> n = hiNode();
2714     if (n != null) {
2715     K last = n.key;
2716     if (inBounds(last))
2717     return last;
2718     }
2719     }
2720     return null;
2721     }
2722     for (;;) {
2723     Node<K,V> n = m.findNear(key, rel);
2724     if (n == null || !inBounds(n.key))
2725     return null;
2726     K k = n.key;
2727     V v = n.getValidValue();
2728     if (v != null)
2729     return k;
2730     }
2731     }
2732 dl 1.1
2733     /* ---------------- Map API methods -------------- */
2734    
2735     public boolean containsKey(Object key) {
2736 dl 1.46 if (key == null) throw new NullPointerException();
2737 dl 1.1 K k = (K)key;
2738 dl 1.46 return inBounds(k) && m.containsKey(k);
2739 dl 1.1 }
2740    
2741     public V get(Object key) {
2742 dl 1.46 if (key == null) throw new NullPointerException();
2743 dl 1.1 K k = (K)key;
2744 dl 1.46 return ((!inBounds(k)) ? null : m.get(k));
2745 dl 1.1 }
2746    
2747     public V put(K key, V value) {
2748 dl 1.46 checkKeyBounds(key);
2749 dl 1.1 return m.put(key, value);
2750     }
2751    
2752     public V remove(Object key) {
2753     K k = (K)key;
2754 dl 1.46 return (!inBounds(k))? null : m.remove(k);
2755 dl 1.1 }
2756    
2757     public int size() {
2758     long count = 0;
2759 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2760 dl 1.9 isBeforeEnd(n);
2761 dl 1.1 n = n.next) {
2762     if (n.getValidValue() != null)
2763     ++count;
2764     }
2765     return count >= Integer.MAX_VALUE? Integer.MAX_VALUE : (int)count;
2766     }
2767    
2768     public boolean isEmpty() {
2769 dl 1.46 return !isBeforeEnd(loNode());
2770 dl 1.1 }
2771    
2772     public boolean containsValue(Object value) {
2773 dl 1.9 if (value == null)
2774 dl 1.1 throw new NullPointerException();
2775 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2776 dl 1.9 isBeforeEnd(n);
2777 dl 1.1 n = n.next) {
2778     V v = n.getValidValue();
2779     if (v != null && value.equals(v))
2780     return true;
2781     }
2782     return false;
2783     }
2784    
2785     public void clear() {
2786 dl 1.46 for (ConcurrentSkipListMap.Node<K,V> n = loNode();
2787 dl 1.9 isBeforeEnd(n);
2788 dl 1.1 n = n.next) {
2789     if (n.getValidValue() != null)
2790     m.remove(n.key);
2791     }
2792     }
2793    
2794     /* ---------------- ConcurrentMap API methods -------------- */
2795    
2796     public V putIfAbsent(K key, V value) {
2797 dl 1.46 checkKeyBounds(key);
2798 dl 1.1 return m.putIfAbsent(key, value);
2799     }
2800    
2801     public boolean remove(Object key, Object value) {
2802     K k = (K)key;
2803 dl 1.46 return inBounds(k) && m.remove(k, value);
2804 dl 1.1 }
2805    
2806     public boolean replace(K key, V oldValue, V newValue) {
2807 dl 1.46 checkKeyBounds(key);
2808 dl 1.1 return m.replace(key, oldValue, newValue);
2809     }
2810    
2811     public V replace(K key, V value) {
2812 dl 1.46 checkKeyBounds(key);
2813 dl 1.1 return m.replace(key, value);
2814     }
2815    
2816     /* ---------------- SortedMap API methods -------------- */
2817    
2818     public Comparator<? super K> comparator() {
2819 dl 1.46 Comparator<? super K> cmp = m.comparator();
2820     if (cmp == null || !isDescending)
2821     return cmp;
2822 dl 1.1 else
2823 dl 1.46 return Collections.reverseOrder(cmp);
2824 dl 1.1 }
2825 dl 1.46
2826     /**
2827     * Utility to create submaps, where given bounds override
2828     * unbounded(null) ones and/or are checked against bounded ones.
2829     */
2830     private SubMap<K,V> newSubMap(K fromKey,
2831     boolean fromInclusive,
2832     K toKey,
2833     boolean toInclusive) {
2834     if (isDescending) { // flip senses
2835     K tk = fromKey;
2836     fromKey = toKey;
2837     toKey = tk;
2838     boolean ti = fromInclusive;
2839     fromInclusive = toInclusive;
2840     toInclusive = ti;
2841     }
2842     if (lo != null) {
2843     if (fromKey == null) {
2844     fromKey = lo;
2845     fromInclusive = loInclusive;
2846     }
2847     else {
2848     int c = m.compare(fromKey, lo);
2849     if (c < 0 || (c == 0 && !loInclusive && fromInclusive))
2850     throw new IllegalArgumentException("key out of range");
2851     }
2852     }
2853     if (hi != null) {
2854     if (toKey == null) {
2855     toKey = hi;
2856     toInclusive = hiInclusive;
2857     }
2858     else {
2859     int c = m.compare(toKey, hi);
2860     if (c > 0 || (c == 0 && !hiInclusive && toInclusive))
2861     throw new IllegalArgumentException("key out of range");
2862     }
2863 dl 1.1 }
2864 dl 1.46 return new SubMap<K,V>(m, fromKey, fromInclusive,
2865     toKey, toInclusive, isDescending);
2866 dl 1.1 }
2867    
2868 dl 1.46 public SubMap<K,V> navigableSubMap(K fromKey,
2869     boolean fromInclusive,
2870     K toKey,
2871     boolean toInclusive) {
2872 dl 1.1 if (fromKey == null || toKey == null)
2873     throw new NullPointerException();
2874 dl 1.46 return newSubMap(fromKey, fromInclusive, toKey, toInclusive);
2875 dl 1.1 }
2876 dl 1.46
2877     public SubMap<K,V> navigableHeadMap(K toKey,
2878     boolean inclusive) {
2879 dl 1.1 if (toKey == null)
2880     throw new NullPointerException();
2881 dl 1.46 return newSubMap(null, false, toKey, inclusive);
2882 dl 1.1 }
2883 dl 1.46
2884     public SubMap<K,V> navigableTailMap(K fromKey,
2885     boolean inclusive) {
2886 dl 1.1 if (fromKey == null)
2887     throw new NullPointerException();
2888 dl 1.46 return newSubMap(fromKey, inclusive, null, false);
2889     }
2890    
2891     public SubMap<K,V> subMap(K fromKey, K toKey) {
2892     return navigableSubMap(fromKey, true, toKey, false);
2893 dl 1.1 }
2894    
2895 dl 1.46 public SubMap<K,V> headMap(K toKey) {
2896     return navigableHeadMap(toKey, false);
2897 dl 1.6 }
2898    
2899 dl 1.46 public SubMap<K,V> tailMap(K fromKey) {
2900     return navigableTailMap(fromKey, true);
2901 dl 1.6 }
2902    
2903 dl 1.46 public SubMap<K,V> descendingMap() {
2904     return new SubMap<K,V>(m, lo, loInclusive,
2905     hi, hiInclusive, !isDescending);
2906 dl 1.6 }
2907    
2908 dl 1.1 /* ---------------- Relational methods -------------- */
2909    
2910     public Map.Entry<K,V> ceilingEntry(K key) {
2911 dl 1.46 return getNearEntry(key, (m.GT|m.EQ));
2912 dl 1.1 }
2913    
2914     public K ceilingKey(K key) {
2915 dl 1.46 return getNearKey(key, (m.GT|m.EQ));
2916 dl 1.1 }
2917    
2918     public Map.Entry<K,V> lowerEntry(K key) {
2919 dl 1.46 return getNearEntry(key, (m.LT));
2920 dl 1.1 }
2921    
2922     public K lowerKey(K key) {
2923 dl 1.46 return getNearKey(key, (m.LT));
2924 dl 1.1 }
2925    
2926     public Map.Entry<K,V> floorEntry(K key) {
2927 dl 1.46 return getNearEntry(key, (m.LT|m.EQ));
2928 dl 1.1 }
2929    
2930     public K floorKey(K key) {
2931 dl 1.46 return getNearKey(key, (m.LT|m.EQ));
2932 dl 1.1 }
2933    
2934     public Map.Entry<K,V> higherEntry(K key) {
2935 dl 1.46 return getNearEntry(key, (m.GT));
2936 dl 1.1 }
2937    
2938     public K higherKey(K key) {
2939 dl 1.46 return getNearKey(key, (m.GT));
2940     }
2941    
2942     public K firstKey() {
2943     return isDescending? highestKey() : lowestKey();
2944     }
2945    
2946     public K lastKey() {
2947     return isDescending? lowestKey() : highestKey();
2948 dl 1.1 }
2949    
2950     public Map.Entry<K,V> firstEntry() {
2951 dl 1.46 return isDescending? highestEntry() : lowestEntry();
2952 dl 1.1 }
2953    
2954     public Map.Entry<K,V> lastEntry() {
2955 dl 1.46 return isDescending? lowestEntry() : highestEntry();
2956 dl 1.1 }
2957    
2958     public Map.Entry<K,V> pollFirstEntry() {
2959 dl 1.46 return isDescending? removeHighest() : removeLowest();
2960 dl 1.1 }
2961    
2962     public Map.Entry<K,V> pollLastEntry() {
2963 dl 1.46 return isDescending? removeLowest() : removeHighest();
2964 dl 1.1 }
2965    
2966     /* ---------------- Submap Views -------------- */
2967    
2968     public Set<K> keySet() {
2969 dl 1.46 KeySet<K> ks = keySetView;
2970     return (ks != null) ? ks : (keySetView = new KeySet(this));
2971 dl 1.1 }
2972    
2973 dl 1.46 public NavigableSet<K> navigableKeySet() {
2974     KeySet<K> ks = keySetView;
2975     return (ks != null) ? ks : (keySetView = new KeySet(this));
2976     }
2977 dl 1.45
2978 dl 1.46 public Collection<V> values() {
2979     Collection<V> vs = valuesView;
2980     return (vs != null) ? vs : (valuesView = new Values(this));
2981 dl 1.1 }
2982    
2983 dl 1.46 public Set<Map.Entry<K,V>> entrySet() {
2984     Set<Map.Entry<K,V>> es = entrySetView;
2985     return (es != null) ? es : (entrySetView = new EntrySet(this));
2986 dl 1.1 }
2987    
2988 dl 1.46 public NavigableSet<K> descendingKeySet() {
2989     return descendingMap().navigableKeySet();
2990 dl 1.1 }
2991    
2992 dl 1.46 Iterator<K> keyIterator() {
2993     return new SubMapKeyIterator();
2994 dl 1.1 }
2995    
2996 dl 1.46 Iterator<V> valueIterator() {
2997     return new SubMapValueIterator();
2998 dl 1.1 }
2999    
3000 dl 1.46 Iterator<Map.Entry<K,V>> entryIterator() {
3001     return new SubMapEntryIterator();
3002 dl 1.1 }
3003    
3004 dl 1.46 /**
3005     * Variant of main Iter class to traverse through submaps.
3006     */
3007     abstract class SubMapIter<T> implements Iterator<T> {
3008     /** the last node returned by next() */
3009     Node<K,V> last;
3010     /** the next node to return from next(); */
3011     Node<K,V> next;
3012     /** Cache of next value field to maintain weak consistency */
3013     Object nextValue;
3014    
3015     SubMapIter() {
3016     for (;;) {
3017     next = isDescending? hiNode() : loNode();
3018     if (next == null)
3019     break;
3020     nextValue = next.value;
3021     if (nextValue != null && nextValue != next) {
3022     if (!inBounds(next.key)) {
3023     next = null;
3024     nextValue = null;
3025     }
3026     break;
3027     }
3028     }
3029 dl 1.1 }
3030 dl 1.46
3031     public final boolean hasNext() {
3032     return next != null;
3033 dl 1.1 }
3034 dl 1.46
3035     final void advance() {
3036     if ((last = next) == null)
3037     throw new NoSuchElementException();
3038     if (isDescending)
3039     descend();
3040     else
3041     ascend();
3042 dl 1.1 }
3043 dl 1.46
3044     private void ascend() {
3045     for (;;) {
3046     next = next.next;
3047     if (next == null)
3048     break;
3049     nextValue = next.value;
3050     if (nextValue != null && nextValue != next) {
3051     if (tooHigh(next.key)) {
3052     next = null;
3053     nextValue = null;
3054     }
3055     break;
3056     }
3057     }
3058     }
3059    
3060     private void descend() {
3061     for (;;) {
3062     next = m.findNear(last.key, LT);
3063     if (next == null)
3064     break;
3065     nextValue = next.value;
3066     if (nextValue != null && nextValue != next) {
3067     if (tooLow(next.key)) {
3068     next = null;
3069     nextValue = null;
3070     }
3071     break;
3072     }
3073     }
3074 dl 1.1 }
3075 dl 1.46
3076     public void remove() {
3077     Node<K,V> l = last;
3078     if (l == null)
3079     throw new IllegalStateException();
3080     m.remove(l.key);
3081 dl 1.1 }
3082 dl 1.46
3083     }
3084    
3085     final class SubMapValueIterator extends SubMapIter<V> {
3086     public V next() {
3087     Object v = nextValue;
3088     advance();
3089     return (V)v;
3090 dl 1.45 }
3091 dl 1.1 }
3092    
3093 dl 1.46 final class SubMapKeyIterator extends SubMapIter<K> {
3094     public K next() {
3095     Node<K,V> n = next;
3096     advance();
3097     return n.key;
3098     }
3099 dl 1.1 }
3100    
3101 dl 1.46 final class SubMapEntryIterator extends SubMapIter<Map.Entry<K,V>> {
3102     public Map.Entry<K,V> next() {
3103     Node<K,V> n = next;
3104     V v = (V)nextValue;
3105     advance();
3106     return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, v);
3107 dl 1.1 }
3108     }
3109     }
3110     }