ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.65
Committed: Tue Feb 22 23:53:32 2011 UTC (13 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.64: +38 -23 lines
Log Message:
Reduce dependencies in static initialization

File Contents

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