ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentSkipListMap.java
Revision: 1.62
Committed: Fri Oct 22 05:49:04 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.61: +4 -2 lines
Log Message:
80 cols

File Contents

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