ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166x/ConcurrentSkipListMap.java
Revision: 1.34
Committed: Mon Jul 27 03:06:08 2015 UTC (8 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.33: +1 -1 lines
Log Message:
whitespace

File Contents

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