ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.60
Committed: Tue Sep 7 23:17:10 2010 UTC (13 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.59: +2 -2 lines
Log Message:
trailing whitespace

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