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