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