ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.79
Committed: Fri Dec 2 14:37:32 2011 UTC (12 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.78: +1 -0 lines
Log Message:
blanket unchecked warning suppression for comparator-using classes

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