rt/emul/compact/src/main/java/java/util/concurrent/CopyOnWriteArrayList.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
 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
jaroslav@1890
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1890
     4
 *
jaroslav@1890
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1890
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1890
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1890
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1890
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1890
    10
 *
jaroslav@1890
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1890
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1890
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1890
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1890
    15
 * accompanied this code).
jaroslav@1890
    16
 *
jaroslav@1890
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1890
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1890
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1890
    20
 *
jaroslav@1890
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1890
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1890
    23
 * questions.
jaroslav@1890
    24
 */
jaroslav@1890
    25
jaroslav@1890
    26
/*
jaroslav@1890
    27
 * Written by Doug Lea with assistance from members of JCP JSR-166
jaroslav@1890
    28
 * Expert Group.  Adapted and released, under explicit permission,
jaroslav@1890
    29
 * from JDK ArrayList.java which carries the following copyright:
jaroslav@1890
    30
 *
jaroslav@1890
    31
 * Copyright 1997 by Sun Microsystems, Inc.,
jaroslav@1890
    32
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
jaroslav@1890
    33
 * All rights reserved.
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.locks.*;
jaroslav@1890
    39
import sun.misc.Unsafe;
jaroslav@1890
    40
jaroslav@1890
    41
/**
jaroslav@1890
    42
 * A thread-safe variant of {@link java.util.ArrayList} in which all mutative
jaroslav@1890
    43
 * operations (<tt>add</tt>, <tt>set</tt>, and so on) are implemented by
jaroslav@1890
    44
 * making a fresh copy of the underlying array.
jaroslav@1890
    45
 *
jaroslav@1890
    46
 * <p> This is ordinarily too costly, but may be <em>more</em> efficient
jaroslav@1890
    47
 * than alternatives when traversal operations vastly outnumber
jaroslav@1890
    48
 * mutations, and is useful when you cannot or don't want to
jaroslav@1890
    49
 * synchronize traversals, yet need to preclude interference among
jaroslav@1890
    50
 * concurrent threads.  The "snapshot" style iterator method uses a
jaroslav@1890
    51
 * reference to the state of the array at the point that the iterator
jaroslav@1890
    52
 * was created. This array never changes during the lifetime of the
jaroslav@1890
    53
 * iterator, so interference is impossible and the iterator is
jaroslav@1890
    54
 * guaranteed not to throw <tt>ConcurrentModificationException</tt>.
jaroslav@1890
    55
 * The iterator will not reflect additions, removals, or changes to
jaroslav@1890
    56
 * the list since the iterator was created.  Element-changing
jaroslav@1890
    57
 * operations on iterators themselves (<tt>remove</tt>, <tt>set</tt>, and
jaroslav@1890
    58
 * <tt>add</tt>) are not supported. These methods throw
jaroslav@1890
    59
 * <tt>UnsupportedOperationException</tt>.
jaroslav@1890
    60
 *
jaroslav@1890
    61
 * <p>All elements are permitted, including <tt>null</tt>.
jaroslav@1890
    62
 *
jaroslav@1890
    63
 * <p>Memory consistency effects: As with other concurrent
jaroslav@1890
    64
 * collections, actions in a thread prior to placing an object into a
jaroslav@1890
    65
 * {@code CopyOnWriteArrayList}
jaroslav@1890
    66
 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
jaroslav@1890
    67
 * actions subsequent to the access or removal of that element from
jaroslav@1890
    68
 * the {@code CopyOnWriteArrayList} in another thread.
jaroslav@1890
    69
 *
jaroslav@1890
    70
 * <p>This class is a member of the
jaroslav@1890
    71
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
jaroslav@1890
    72
 * Java Collections Framework</a>.
jaroslav@1890
    73
 *
jaroslav@1890
    74
 * @since 1.5
jaroslav@1890
    75
 * @author Doug Lea
jaroslav@1890
    76
 * @param <E> the type of elements held in this collection
jaroslav@1890
    77
 */
jaroslav@1890
    78
public class CopyOnWriteArrayList<E>
jaroslav@1890
    79
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
jaroslav@1890
    80
    private static final long serialVersionUID = 8673264195747942595L;
jaroslav@1890
    81
jaroslav@1890
    82
    /** The lock protecting all mutators */
jaroslav@1890
    83
    transient final ReentrantLock lock = new ReentrantLock();
jaroslav@1890
    84
jaroslav@1890
    85
    /** The array, accessed only via getArray/setArray. */
jaroslav@1890
    86
    private volatile transient Object[] array;
jaroslav@1890
    87
jaroslav@1890
    88
    /**
jaroslav@1890
    89
     * Gets the array.  Non-private so as to also be accessible
jaroslav@1890
    90
     * from CopyOnWriteArraySet class.
jaroslav@1890
    91
     */
jaroslav@1890
    92
    final Object[] getArray() {
jaroslav@1890
    93
        return array;
jaroslav@1890
    94
    }
jaroslav@1890
    95
jaroslav@1890
    96
    /**
jaroslav@1890
    97
     * Sets the array.
jaroslav@1890
    98
     */
jaroslav@1890
    99
    final void setArray(Object[] a) {
jaroslav@1890
   100
        array = a;
jaroslav@1890
   101
    }
jaroslav@1890
   102
jaroslav@1890
   103
    /**
jaroslav@1890
   104
     * Creates an empty list.
jaroslav@1890
   105
     */
jaroslav@1890
   106
    public CopyOnWriteArrayList() {
jaroslav@1890
   107
        setArray(new Object[0]);
jaroslav@1890
   108
    }
jaroslav@1890
   109
jaroslav@1890
   110
    /**
jaroslav@1890
   111
     * Creates a list containing the elements of the specified
jaroslav@1890
   112
     * collection, in the order they are returned by the collection's
jaroslav@1890
   113
     * iterator.
jaroslav@1890
   114
     *
jaroslav@1890
   115
     * @param c the collection of initially held elements
jaroslav@1890
   116
     * @throws NullPointerException if the specified collection is null
jaroslav@1890
   117
     */
jaroslav@1890
   118
    public CopyOnWriteArrayList(Collection<? extends E> c) {
jaroslav@1890
   119
        Object[] elements = c.toArray();
jaroslav@1890
   120
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
jaroslav@1890
   121
        if (elements.getClass() != Object[].class)
jaroslav@1890
   122
            elements = Arrays.copyOf(elements, elements.length, Object[].class);
jaroslav@1890
   123
        setArray(elements);
jaroslav@1890
   124
    }
jaroslav@1890
   125
jaroslav@1890
   126
    /**
jaroslav@1890
   127
     * Creates a list holding a copy of the given array.
jaroslav@1890
   128
     *
jaroslav@1890
   129
     * @param toCopyIn the array (a copy of this array is used as the
jaroslav@1890
   130
     *        internal array)
jaroslav@1890
   131
     * @throws NullPointerException if the specified array is null
jaroslav@1890
   132
     */
jaroslav@1890
   133
    public CopyOnWriteArrayList(E[] toCopyIn) {
jaroslav@1890
   134
        setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
jaroslav@1890
   135
    }
jaroslav@1890
   136
jaroslav@1890
   137
    /**
jaroslav@1890
   138
     * Returns the number of elements in this list.
jaroslav@1890
   139
     *
jaroslav@1890
   140
     * @return the number of elements in this list
jaroslav@1890
   141
     */
jaroslav@1890
   142
    public int size() {
jaroslav@1890
   143
        return getArray().length;
jaroslav@1890
   144
    }
jaroslav@1890
   145
jaroslav@1890
   146
    /**
jaroslav@1890
   147
     * Returns <tt>true</tt> if this list contains no elements.
jaroslav@1890
   148
     *
jaroslav@1890
   149
     * @return <tt>true</tt> if this list contains no elements
jaroslav@1890
   150
     */
jaroslav@1890
   151
    public boolean isEmpty() {
jaroslav@1890
   152
        return size() == 0;
jaroslav@1890
   153
    }
jaroslav@1890
   154
jaroslav@1890
   155
    /**
jaroslav@1890
   156
     * Test for equality, coping with nulls.
jaroslav@1890
   157
     */
jaroslav@1890
   158
    private static boolean eq(Object o1, Object o2) {
jaroslav@1890
   159
        return (o1 == null ? o2 == null : o1.equals(o2));
jaroslav@1890
   160
    }
jaroslav@1890
   161
jaroslav@1890
   162
    /**
jaroslav@1890
   163
     * static version of indexOf, to allow repeated calls without
jaroslav@1890
   164
     * needing to re-acquire array each time.
jaroslav@1890
   165
     * @param o element to search for
jaroslav@1890
   166
     * @param elements the array
jaroslav@1890
   167
     * @param index first index to search
jaroslav@1890
   168
     * @param fence one past last index to search
jaroslav@1890
   169
     * @return index of element, or -1 if absent
jaroslav@1890
   170
     */
jaroslav@1890
   171
    private static int indexOf(Object o, Object[] elements,
jaroslav@1890
   172
                               int index, int fence) {
jaroslav@1890
   173
        if (o == null) {
jaroslav@1890
   174
            for (int i = index; i < fence; i++)
jaroslav@1890
   175
                if (elements[i] == null)
jaroslav@1890
   176
                    return i;
jaroslav@1890
   177
        } else {
jaroslav@1890
   178
            for (int i = index; i < fence; i++)
jaroslav@1890
   179
                if (o.equals(elements[i]))
jaroslav@1890
   180
                    return i;
jaroslav@1890
   181
        }
jaroslav@1890
   182
        return -1;
jaroslav@1890
   183
    }
jaroslav@1890
   184
jaroslav@1890
   185
    /**
jaroslav@1890
   186
     * static version of lastIndexOf.
jaroslav@1890
   187
     * @param o element to search for
jaroslav@1890
   188
     * @param elements the array
jaroslav@1890
   189
     * @param index first index to search
jaroslav@1890
   190
     * @return index of element, or -1 if absent
jaroslav@1890
   191
     */
jaroslav@1890
   192
    private static int lastIndexOf(Object o, Object[] elements, int index) {
jaroslav@1890
   193
        if (o == null) {
jaroslav@1890
   194
            for (int i = index; i >= 0; i--)
jaroslav@1890
   195
                if (elements[i] == null)
jaroslav@1890
   196
                    return i;
jaroslav@1890
   197
        } else {
jaroslav@1890
   198
            for (int i = index; i >= 0; i--)
jaroslav@1890
   199
                if (o.equals(elements[i]))
jaroslav@1890
   200
                    return i;
jaroslav@1890
   201
        }
jaroslav@1890
   202
        return -1;
jaroslav@1890
   203
    }
jaroslav@1890
   204
jaroslav@1890
   205
    /**
jaroslav@1890
   206
     * Returns <tt>true</tt> if this list contains the specified element.
jaroslav@1890
   207
     * More formally, returns <tt>true</tt> if and only if this list contains
jaroslav@1890
   208
     * at least one element <tt>e</tt> such that
jaroslav@1890
   209
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
jaroslav@1890
   210
     *
jaroslav@1890
   211
     * @param o element whose presence in this list is to be tested
jaroslav@1890
   212
     * @return <tt>true</tt> if this list contains the specified element
jaroslav@1890
   213
     */
jaroslav@1890
   214
    public boolean contains(Object o) {
jaroslav@1890
   215
        Object[] elements = getArray();
jaroslav@1890
   216
        return indexOf(o, elements, 0, elements.length) >= 0;
jaroslav@1890
   217
    }
jaroslav@1890
   218
jaroslav@1890
   219
    /**
jaroslav@1890
   220
     * {@inheritDoc}
jaroslav@1890
   221
     */
jaroslav@1890
   222
    public int indexOf(Object o) {
jaroslav@1890
   223
        Object[] elements = getArray();
jaroslav@1890
   224
        return indexOf(o, elements, 0, elements.length);
jaroslav@1890
   225
    }
jaroslav@1890
   226
jaroslav@1890
   227
    /**
jaroslav@1890
   228
     * Returns the index of the first occurrence of the specified element in
jaroslav@1890
   229
     * this list, searching forwards from <tt>index</tt>, or returns -1 if
jaroslav@1890
   230
     * the element is not found.
jaroslav@1890
   231
     * More formally, returns the lowest index <tt>i</tt> such that
jaroslav@1890
   232
     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
jaroslav@1890
   233
     * or -1 if there is no such index.
jaroslav@1890
   234
     *
jaroslav@1890
   235
     * @param e element to search for
jaroslav@1890
   236
     * @param index index to start searching from
jaroslav@1890
   237
     * @return the index of the first occurrence of the element in
jaroslav@1890
   238
     *         this list at position <tt>index</tt> or later in the list;
jaroslav@1890
   239
     *         <tt>-1</tt> if the element is not found.
jaroslav@1890
   240
     * @throws IndexOutOfBoundsException if the specified index is negative
jaroslav@1890
   241
     */
jaroslav@1890
   242
    public int indexOf(E e, int index) {
jaroslav@1890
   243
        Object[] elements = getArray();
jaroslav@1890
   244
        return indexOf(e, elements, index, elements.length);
jaroslav@1890
   245
    }
jaroslav@1890
   246
jaroslav@1890
   247
    /**
jaroslav@1890
   248
     * {@inheritDoc}
jaroslav@1890
   249
     */
jaroslav@1890
   250
    public int lastIndexOf(Object o) {
jaroslav@1890
   251
        Object[] elements = getArray();
jaroslav@1890
   252
        return lastIndexOf(o, elements, elements.length - 1);
jaroslav@1890
   253
    }
jaroslav@1890
   254
jaroslav@1890
   255
    /**
jaroslav@1890
   256
     * Returns the index of the last occurrence of the specified element in
jaroslav@1890
   257
     * this list, searching backwards from <tt>index</tt>, or returns -1 if
jaroslav@1890
   258
     * the element is not found.
jaroslav@1890
   259
     * More formally, returns the highest index <tt>i</tt> such that
jaroslav@1890
   260
     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
jaroslav@1890
   261
     * or -1 if there is no such index.
jaroslav@1890
   262
     *
jaroslav@1890
   263
     * @param e element to search for
jaroslav@1890
   264
     * @param index index to start searching backwards from
jaroslav@1890
   265
     * @return the index of the last occurrence of the element at position
jaroslav@1890
   266
     *         less than or equal to <tt>index</tt> in this list;
jaroslav@1890
   267
     *         -1 if the element is not found.
jaroslav@1890
   268
     * @throws IndexOutOfBoundsException if the specified index is greater
jaroslav@1890
   269
     *         than or equal to the current size of this list
jaroslav@1890
   270
     */
jaroslav@1890
   271
    public int lastIndexOf(E e, int index) {
jaroslav@1890
   272
        Object[] elements = getArray();
jaroslav@1890
   273
        return lastIndexOf(e, elements, index);
jaroslav@1890
   274
    }
jaroslav@1890
   275
jaroslav@1890
   276
    /**
jaroslav@1890
   277
     * Returns a shallow copy of this list.  (The elements themselves
jaroslav@1890
   278
     * are not copied.)
jaroslav@1890
   279
     *
jaroslav@1890
   280
     * @return a clone of this list
jaroslav@1890
   281
     */
jaroslav@1890
   282
    public Object clone() {
jaroslav@1890
   283
        try {
jaroslav@1890
   284
            CopyOnWriteArrayList c = (CopyOnWriteArrayList)(super.clone());
jaroslav@1890
   285
            c.resetLock();
jaroslav@1890
   286
            return c;
jaroslav@1890
   287
        } catch (CloneNotSupportedException e) {
jaroslav@1890
   288
            // this shouldn't happen, since we are Cloneable
jaroslav@1890
   289
            throw new InternalError();
jaroslav@1890
   290
        }
jaroslav@1890
   291
    }
jaroslav@1890
   292
jaroslav@1890
   293
    /**
jaroslav@1890
   294
     * Returns an array containing all of the elements in this list
jaroslav@1890
   295
     * in proper sequence (from first to last element).
jaroslav@1890
   296
     *
jaroslav@1890
   297
     * <p>The returned array will be "safe" in that no references to it are
jaroslav@1890
   298
     * maintained by this list.  (In other words, this method must allocate
jaroslav@1890
   299
     * a new array).  The caller is thus free to modify the returned array.
jaroslav@1890
   300
     *
jaroslav@1890
   301
     * <p>This method acts as bridge between array-based and collection-based
jaroslav@1890
   302
     * APIs.
jaroslav@1890
   303
     *
jaroslav@1890
   304
     * @return an array containing all the elements in this list
jaroslav@1890
   305
     */
jaroslav@1890
   306
    public Object[] toArray() {
jaroslav@1890
   307
        Object[] elements = getArray();
jaroslav@1890
   308
        return Arrays.copyOf(elements, elements.length);
jaroslav@1890
   309
    }
jaroslav@1890
   310
jaroslav@1890
   311
    /**
jaroslav@1890
   312
     * Returns an array containing all of the elements in this list in
jaroslav@1890
   313
     * proper sequence (from first to last element); the runtime type of
jaroslav@1890
   314
     * the returned array is that of the specified array.  If the list fits
jaroslav@1890
   315
     * in the specified array, it is returned therein.  Otherwise, a new
jaroslav@1890
   316
     * array is allocated with the runtime type of the specified array and
jaroslav@1890
   317
     * the size of this list.
jaroslav@1890
   318
     *
jaroslav@1890
   319
     * <p>If this list fits in the specified array with room to spare
jaroslav@1890
   320
     * (i.e., the array has more elements than this list), the element in
jaroslav@1890
   321
     * the array immediately following the end of the list is set to
jaroslav@1890
   322
     * <tt>null</tt>.  (This is useful in determining the length of this
jaroslav@1890
   323
     * list <i>only</i> if the caller knows that this list does not contain
jaroslav@1890
   324
     * any null elements.)
jaroslav@1890
   325
     *
jaroslav@1890
   326
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
jaroslav@1890
   327
     * array-based and collection-based APIs.  Further, this method allows
jaroslav@1890
   328
     * precise control over the runtime type of the output array, and may,
jaroslav@1890
   329
     * under certain circumstances, be used to save allocation costs.
jaroslav@1890
   330
     *
jaroslav@1890
   331
     * <p>Suppose <tt>x</tt> is a list known to contain only strings.
jaroslav@1890
   332
     * The following code can be used to dump the list into a newly
jaroslav@1890
   333
     * allocated array of <tt>String</tt>:
jaroslav@1890
   334
     *
jaroslav@1890
   335
     * <pre>
jaroslav@1890
   336
     *     String[] y = x.toArray(new String[0]);</pre>
jaroslav@1890
   337
     *
jaroslav@1890
   338
     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
jaroslav@1890
   339
     * <tt>toArray()</tt>.
jaroslav@1890
   340
     *
jaroslav@1890
   341
     * @param a the array into which the elements of the list are to
jaroslav@1890
   342
     *          be stored, if it is big enough; otherwise, a new array of the
jaroslav@1890
   343
     *          same runtime type is allocated for this purpose.
jaroslav@1890
   344
     * @return an array containing all the elements in this list
jaroslav@1890
   345
     * @throws ArrayStoreException if the runtime type of the specified array
jaroslav@1890
   346
     *         is not a supertype of the runtime type of every element in
jaroslav@1890
   347
     *         this list
jaroslav@1890
   348
     * @throws NullPointerException if the specified array is null
jaroslav@1890
   349
     */
jaroslav@1890
   350
    @SuppressWarnings("unchecked")
jaroslav@1890
   351
    public <T> T[] toArray(T a[]) {
jaroslav@1890
   352
        Object[] elements = getArray();
jaroslav@1890
   353
        int len = elements.length;
jaroslav@1890
   354
        if (a.length < len)
jaroslav@1890
   355
            return (T[]) Arrays.copyOf(elements, len, a.getClass());
jaroslav@1890
   356
        else {
jaroslav@1890
   357
            System.arraycopy(elements, 0, a, 0, len);
jaroslav@1890
   358
            if (a.length > len)
jaroslav@1890
   359
                a[len] = null;
jaroslav@1890
   360
            return a;
jaroslav@1890
   361
        }
jaroslav@1890
   362
    }
jaroslav@1890
   363
jaroslav@1890
   364
    // Positional Access Operations
jaroslav@1890
   365
jaroslav@1890
   366
    @SuppressWarnings("unchecked")
jaroslav@1890
   367
    private E get(Object[] a, int index) {
jaroslav@1890
   368
        return (E) a[index];
jaroslav@1890
   369
    }
jaroslav@1890
   370
jaroslav@1890
   371
    /**
jaroslav@1890
   372
     * {@inheritDoc}
jaroslav@1890
   373
     *
jaroslav@1890
   374
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   375
     */
jaroslav@1890
   376
    public E get(int index) {
jaroslav@1890
   377
        return get(getArray(), index);
jaroslav@1890
   378
    }
jaroslav@1890
   379
jaroslav@1890
   380
    /**
jaroslav@1890
   381
     * Replaces the element at the specified position in this list with the
jaroslav@1890
   382
     * specified element.
jaroslav@1890
   383
     *
jaroslav@1890
   384
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   385
     */
jaroslav@1890
   386
    public E set(int index, E element) {
jaroslav@1890
   387
        final ReentrantLock lock = this.lock;
jaroslav@1890
   388
        lock.lock();
jaroslav@1890
   389
        try {
jaroslav@1890
   390
            Object[] elements = getArray();
jaroslav@1890
   391
            E oldValue = get(elements, index);
jaroslav@1890
   392
jaroslav@1890
   393
            if (oldValue != element) {
jaroslav@1890
   394
                int len = elements.length;
jaroslav@1890
   395
                Object[] newElements = Arrays.copyOf(elements, len);
jaroslav@1890
   396
                newElements[index] = element;
jaroslav@1890
   397
                setArray(newElements);
jaroslav@1890
   398
            } else {
jaroslav@1890
   399
                // Not quite a no-op; ensures volatile write semantics
jaroslav@1890
   400
                setArray(elements);
jaroslav@1890
   401
            }
jaroslav@1890
   402
            return oldValue;
jaroslav@1890
   403
        } finally {
jaroslav@1890
   404
            lock.unlock();
jaroslav@1890
   405
        }
jaroslav@1890
   406
    }
jaroslav@1890
   407
jaroslav@1890
   408
    /**
jaroslav@1890
   409
     * Appends the specified element to the end of this list.
jaroslav@1890
   410
     *
jaroslav@1890
   411
     * @param e element to be appended to this list
jaroslav@1890
   412
     * @return <tt>true</tt> (as specified by {@link Collection#add})
jaroslav@1890
   413
     */
jaroslav@1890
   414
    public boolean add(E e) {
jaroslav@1890
   415
        final ReentrantLock lock = this.lock;
jaroslav@1890
   416
        lock.lock();
jaroslav@1890
   417
        try {
jaroslav@1890
   418
            Object[] elements = getArray();
jaroslav@1890
   419
            int len = elements.length;
jaroslav@1890
   420
            Object[] newElements = Arrays.copyOf(elements, len + 1);
jaroslav@1890
   421
            newElements[len] = e;
jaroslav@1890
   422
            setArray(newElements);
jaroslav@1890
   423
            return true;
jaroslav@1890
   424
        } finally {
jaroslav@1890
   425
            lock.unlock();
jaroslav@1890
   426
        }
jaroslav@1890
   427
    }
jaroslav@1890
   428
jaroslav@1890
   429
    /**
jaroslav@1890
   430
     * Inserts the specified element at the specified position in this
jaroslav@1890
   431
     * list. Shifts the element currently at that position (if any) and
jaroslav@1890
   432
     * any subsequent elements to the right (adds one to their indices).
jaroslav@1890
   433
     *
jaroslav@1890
   434
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   435
     */
jaroslav@1890
   436
    public void add(int index, E element) {
jaroslav@1890
   437
        final ReentrantLock lock = this.lock;
jaroslav@1890
   438
        lock.lock();
jaroslav@1890
   439
        try {
jaroslav@1890
   440
            Object[] elements = getArray();
jaroslav@1890
   441
            int len = elements.length;
jaroslav@1890
   442
            if (index > len || index < 0)
jaroslav@1890
   443
                throw new IndexOutOfBoundsException("Index: "+index+
jaroslav@1890
   444
                                                    ", Size: "+len);
jaroslav@1890
   445
            Object[] newElements;
jaroslav@1890
   446
            int numMoved = len - index;
jaroslav@1890
   447
            if (numMoved == 0)
jaroslav@1890
   448
                newElements = Arrays.copyOf(elements, len + 1);
jaroslav@1890
   449
            else {
jaroslav@1890
   450
                newElements = new Object[len + 1];
jaroslav@1890
   451
                System.arraycopy(elements, 0, newElements, 0, index);
jaroslav@1890
   452
                System.arraycopy(elements, index, newElements, index + 1,
jaroslav@1890
   453
                                 numMoved);
jaroslav@1890
   454
            }
jaroslav@1890
   455
            newElements[index] = element;
jaroslav@1890
   456
            setArray(newElements);
jaroslav@1890
   457
        } finally {
jaroslav@1890
   458
            lock.unlock();
jaroslav@1890
   459
        }
jaroslav@1890
   460
    }
jaroslav@1890
   461
jaroslav@1890
   462
    /**
jaroslav@1890
   463
     * Removes the element at the specified position in this list.
jaroslav@1890
   464
     * Shifts any subsequent elements to the left (subtracts one from their
jaroslav@1890
   465
     * indices).  Returns the element that was removed from the list.
jaroslav@1890
   466
     *
jaroslav@1890
   467
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   468
     */
jaroslav@1890
   469
    public E remove(int index) {
jaroslav@1890
   470
        final ReentrantLock lock = this.lock;
jaroslav@1890
   471
        lock.lock();
jaroslav@1890
   472
        try {
jaroslav@1890
   473
            Object[] elements = getArray();
jaroslav@1890
   474
            int len = elements.length;
jaroslav@1890
   475
            E oldValue = get(elements, index);
jaroslav@1890
   476
            int numMoved = len - index - 1;
jaroslav@1890
   477
            if (numMoved == 0)
jaroslav@1890
   478
                setArray(Arrays.copyOf(elements, len - 1));
jaroslav@1890
   479
            else {
jaroslav@1890
   480
                Object[] newElements = new Object[len - 1];
jaroslav@1890
   481
                System.arraycopy(elements, 0, newElements, 0, index);
jaroslav@1890
   482
                System.arraycopy(elements, index + 1, newElements, index,
jaroslav@1890
   483
                                 numMoved);
jaroslav@1890
   484
                setArray(newElements);
jaroslav@1890
   485
            }
jaroslav@1890
   486
            return oldValue;
jaroslav@1890
   487
        } finally {
jaroslav@1890
   488
            lock.unlock();
jaroslav@1890
   489
        }
jaroslav@1890
   490
    }
jaroslav@1890
   491
jaroslav@1890
   492
    /**
jaroslav@1890
   493
     * Removes the first occurrence of the specified element from this list,
jaroslav@1890
   494
     * if it is present.  If this list does not contain the element, it is
jaroslav@1890
   495
     * unchanged.  More formally, removes the element with the lowest index
jaroslav@1890
   496
     * <tt>i</tt> such that
jaroslav@1890
   497
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
jaroslav@1890
   498
     * (if such an element exists).  Returns <tt>true</tt> if this list
jaroslav@1890
   499
     * contained the specified element (or equivalently, if this list
jaroslav@1890
   500
     * changed as a result of the call).
jaroslav@1890
   501
     *
jaroslav@1890
   502
     * @param o element to be removed from this list, if present
jaroslav@1890
   503
     * @return <tt>true</tt> if this list contained the specified element
jaroslav@1890
   504
     */
jaroslav@1890
   505
    public boolean remove(Object o) {
jaroslav@1890
   506
        final ReentrantLock lock = this.lock;
jaroslav@1890
   507
        lock.lock();
jaroslav@1890
   508
        try {
jaroslav@1890
   509
            Object[] elements = getArray();
jaroslav@1890
   510
            int len = elements.length;
jaroslav@1890
   511
            if (len != 0) {
jaroslav@1890
   512
                // Copy while searching for element to remove
jaroslav@1890
   513
                // This wins in the normal case of element being present
jaroslav@1890
   514
                int newlen = len - 1;
jaroslav@1890
   515
                Object[] newElements = new Object[newlen];
jaroslav@1890
   516
jaroslav@1890
   517
                for (int i = 0; i < newlen; ++i) {
jaroslav@1890
   518
                    if (eq(o, elements[i])) {
jaroslav@1890
   519
                        // found one;  copy remaining and exit
jaroslav@1890
   520
                        for (int k = i + 1; k < len; ++k)
jaroslav@1890
   521
                            newElements[k-1] = elements[k];
jaroslav@1890
   522
                        setArray(newElements);
jaroslav@1890
   523
                        return true;
jaroslav@1890
   524
                    } else
jaroslav@1890
   525
                        newElements[i] = elements[i];
jaroslav@1890
   526
                }
jaroslav@1890
   527
jaroslav@1890
   528
                // special handling for last cell
jaroslav@1890
   529
                if (eq(o, elements[newlen])) {
jaroslav@1890
   530
                    setArray(newElements);
jaroslav@1890
   531
                    return true;
jaroslav@1890
   532
                }
jaroslav@1890
   533
            }
jaroslav@1890
   534
            return false;
jaroslav@1890
   535
        } finally {
jaroslav@1890
   536
            lock.unlock();
jaroslav@1890
   537
        }
jaroslav@1890
   538
    }
jaroslav@1890
   539
jaroslav@1890
   540
    /**
jaroslav@1890
   541
     * Removes from this list all of the elements whose index is between
jaroslav@1890
   542
     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
jaroslav@1890
   543
     * Shifts any succeeding elements to the left (reduces their index).
jaroslav@1890
   544
     * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
jaroslav@1890
   545
     * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
jaroslav@1890
   546
     *
jaroslav@1890
   547
     * @param fromIndex index of first element to be removed
jaroslav@1890
   548
     * @param toIndex index after last element to be removed
jaroslav@1890
   549
     * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
jaroslav@1890
   550
     *         ({@code{fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
jaroslav@1890
   551
     */
jaroslav@1890
   552
    private void removeRange(int fromIndex, int toIndex) {
jaroslav@1890
   553
        final ReentrantLock lock = this.lock;
jaroslav@1890
   554
        lock.lock();
jaroslav@1890
   555
        try {
jaroslav@1890
   556
            Object[] elements = getArray();
jaroslav@1890
   557
            int len = elements.length;
jaroslav@1890
   558
jaroslav@1890
   559
            if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
jaroslav@1890
   560
                throw new IndexOutOfBoundsException();
jaroslav@1890
   561
            int newlen = len - (toIndex - fromIndex);
jaroslav@1890
   562
            int numMoved = len - toIndex;
jaroslav@1890
   563
            if (numMoved == 0)
jaroslav@1890
   564
                setArray(Arrays.copyOf(elements, newlen));
jaroslav@1890
   565
            else {
jaroslav@1890
   566
                Object[] newElements = new Object[newlen];
jaroslav@1890
   567
                System.arraycopy(elements, 0, newElements, 0, fromIndex);
jaroslav@1890
   568
                System.arraycopy(elements, toIndex, newElements,
jaroslav@1890
   569
                                 fromIndex, numMoved);
jaroslav@1890
   570
                setArray(newElements);
jaroslav@1890
   571
            }
jaroslav@1890
   572
        } finally {
jaroslav@1890
   573
            lock.unlock();
jaroslav@1890
   574
        }
jaroslav@1890
   575
    }
jaroslav@1890
   576
jaroslav@1890
   577
    /**
jaroslav@1890
   578
     * Append the element if not present.
jaroslav@1890
   579
     *
jaroslav@1890
   580
     * @param e element to be added to this list, if absent
jaroslav@1890
   581
     * @return <tt>true</tt> if the element was added
jaroslav@1890
   582
     */
jaroslav@1890
   583
    public boolean addIfAbsent(E e) {
jaroslav@1890
   584
        final ReentrantLock lock = this.lock;
jaroslav@1890
   585
        lock.lock();
jaroslav@1890
   586
        try {
jaroslav@1890
   587
            // Copy while checking if already present.
jaroslav@1890
   588
            // This wins in the most common case where it is not present
jaroslav@1890
   589
            Object[] elements = getArray();
jaroslav@1890
   590
            int len = elements.length;
jaroslav@1890
   591
            Object[] newElements = new Object[len + 1];
jaroslav@1890
   592
            for (int i = 0; i < len; ++i) {
jaroslav@1890
   593
                if (eq(e, elements[i]))
jaroslav@1890
   594
                    return false; // exit, throwing away copy
jaroslav@1890
   595
                else
jaroslav@1890
   596
                    newElements[i] = elements[i];
jaroslav@1890
   597
            }
jaroslav@1890
   598
            newElements[len] = e;
jaroslav@1890
   599
            setArray(newElements);
jaroslav@1890
   600
            return true;
jaroslav@1890
   601
        } finally {
jaroslav@1890
   602
            lock.unlock();
jaroslav@1890
   603
        }
jaroslav@1890
   604
    }
jaroslav@1890
   605
jaroslav@1890
   606
    /**
jaroslav@1890
   607
     * Returns <tt>true</tt> if this list contains all of the elements of the
jaroslav@1890
   608
     * specified collection.
jaroslav@1890
   609
     *
jaroslav@1890
   610
     * @param c collection to be checked for containment in this list
jaroslav@1890
   611
     * @return <tt>true</tt> if this list contains all of the elements of the
jaroslav@1890
   612
     *         specified collection
jaroslav@1890
   613
     * @throws NullPointerException if the specified collection is null
jaroslav@1890
   614
     * @see #contains(Object)
jaroslav@1890
   615
     */
jaroslav@1890
   616
    public boolean containsAll(Collection<?> c) {
jaroslav@1890
   617
        Object[] elements = getArray();
jaroslav@1890
   618
        int len = elements.length;
jaroslav@1890
   619
        for (Object e : c) {
jaroslav@1890
   620
            if (indexOf(e, elements, 0, len) < 0)
jaroslav@1890
   621
                return false;
jaroslav@1890
   622
        }
jaroslav@1890
   623
        return true;
jaroslav@1890
   624
    }
jaroslav@1890
   625
jaroslav@1890
   626
    /**
jaroslav@1890
   627
     * Removes from this list all of its elements that are contained in
jaroslav@1890
   628
     * the specified collection. This is a particularly expensive operation
jaroslav@1890
   629
     * in this class because of the need for an internal temporary array.
jaroslav@1890
   630
     *
jaroslav@1890
   631
     * @param c collection containing elements to be removed from this list
jaroslav@1890
   632
     * @return <tt>true</tt> if this list changed as a result of the call
jaroslav@1890
   633
     * @throws ClassCastException if the class of an element of this list
jaroslav@1890
   634
     *         is incompatible with the specified collection
jaroslav@1890
   635
     *         (<a href="../Collection.html#optional-restrictions">optional</a>)
jaroslav@1890
   636
     * @throws NullPointerException if this list contains a null element and the
jaroslav@1890
   637
     *         specified collection does not permit null elements
jaroslav@1890
   638
     *         (<a href="../Collection.html#optional-restrictions">optional</a>),
jaroslav@1890
   639
     *         or if the specified collection is null
jaroslav@1890
   640
     * @see #remove(Object)
jaroslav@1890
   641
     */
jaroslav@1890
   642
    public boolean removeAll(Collection<?> c) {
jaroslav@1890
   643
        final ReentrantLock lock = this.lock;
jaroslav@1890
   644
        lock.lock();
jaroslav@1890
   645
        try {
jaroslav@1890
   646
            Object[] elements = getArray();
jaroslav@1890
   647
            int len = elements.length;
jaroslav@1890
   648
            if (len != 0) {
jaroslav@1890
   649
                // temp array holds those elements we know we want to keep
jaroslav@1890
   650
                int newlen = 0;
jaroslav@1890
   651
                Object[] temp = new Object[len];
jaroslav@1890
   652
                for (int i = 0; i < len; ++i) {
jaroslav@1890
   653
                    Object element = elements[i];
jaroslav@1890
   654
                    if (!c.contains(element))
jaroslav@1890
   655
                        temp[newlen++] = element;
jaroslav@1890
   656
                }
jaroslav@1890
   657
                if (newlen != len) {
jaroslav@1890
   658
                    setArray(Arrays.copyOf(temp, newlen));
jaroslav@1890
   659
                    return true;
jaroslav@1890
   660
                }
jaroslav@1890
   661
            }
jaroslav@1890
   662
            return false;
jaroslav@1890
   663
        } finally {
jaroslav@1890
   664
            lock.unlock();
jaroslav@1890
   665
        }
jaroslav@1890
   666
    }
jaroslav@1890
   667
jaroslav@1890
   668
    /**
jaroslav@1890
   669
     * Retains only the elements in this list that are contained in the
jaroslav@1890
   670
     * specified collection.  In other words, removes from this list all of
jaroslav@1890
   671
     * its elements that are not contained in the specified collection.
jaroslav@1890
   672
     *
jaroslav@1890
   673
     * @param c collection containing elements to be retained in this list
jaroslav@1890
   674
     * @return <tt>true</tt> if this list changed as a result of the call
jaroslav@1890
   675
     * @throws ClassCastException if the class of an element of this list
jaroslav@1890
   676
     *         is incompatible with the specified collection
jaroslav@1890
   677
     *         (<a href="../Collection.html#optional-restrictions">optional</a>)
jaroslav@1890
   678
     * @throws NullPointerException if this list contains a null element and the
jaroslav@1890
   679
     *         specified collection does not permit null elements
jaroslav@1890
   680
     *         (<a href="../Collection.html#optional-restrictions">optional</a>),
jaroslav@1890
   681
     *         or if the specified collection is null
jaroslav@1890
   682
     * @see #remove(Object)
jaroslav@1890
   683
     */
jaroslav@1890
   684
    public boolean retainAll(Collection<?> c) {
jaroslav@1890
   685
        final ReentrantLock lock = this.lock;
jaroslav@1890
   686
        lock.lock();
jaroslav@1890
   687
        try {
jaroslav@1890
   688
            Object[] elements = getArray();
jaroslav@1890
   689
            int len = elements.length;
jaroslav@1890
   690
            if (len != 0) {
jaroslav@1890
   691
                // temp array holds those elements we know we want to keep
jaroslav@1890
   692
                int newlen = 0;
jaroslav@1890
   693
                Object[] temp = new Object[len];
jaroslav@1890
   694
                for (int i = 0; i < len; ++i) {
jaroslav@1890
   695
                    Object element = elements[i];
jaroslav@1890
   696
                    if (c.contains(element))
jaroslav@1890
   697
                        temp[newlen++] = element;
jaroslav@1890
   698
                }
jaroslav@1890
   699
                if (newlen != len) {
jaroslav@1890
   700
                    setArray(Arrays.copyOf(temp, newlen));
jaroslav@1890
   701
                    return true;
jaroslav@1890
   702
                }
jaroslav@1890
   703
            }
jaroslav@1890
   704
            return false;
jaroslav@1890
   705
        } finally {
jaroslav@1890
   706
            lock.unlock();
jaroslav@1890
   707
        }
jaroslav@1890
   708
    }
jaroslav@1890
   709
jaroslav@1890
   710
    /**
jaroslav@1890
   711
     * Appends all of the elements in the specified collection that
jaroslav@1890
   712
     * are not already contained in this list, to the end of
jaroslav@1890
   713
     * this list, in the order that they are returned by the
jaroslav@1890
   714
     * specified collection's iterator.
jaroslav@1890
   715
     *
jaroslav@1890
   716
     * @param c collection containing elements to be added to this list
jaroslav@1890
   717
     * @return the number of elements added
jaroslav@1890
   718
     * @throws NullPointerException if the specified collection is null
jaroslav@1890
   719
     * @see #addIfAbsent(Object)
jaroslav@1890
   720
     */
jaroslav@1890
   721
    public int addAllAbsent(Collection<? extends E> c) {
jaroslav@1890
   722
        Object[] cs = c.toArray();
jaroslav@1890
   723
        if (cs.length == 0)
jaroslav@1890
   724
            return 0;
jaroslav@1890
   725
        Object[] uniq = new Object[cs.length];
jaroslav@1890
   726
        final ReentrantLock lock = this.lock;
jaroslav@1890
   727
        lock.lock();
jaroslav@1890
   728
        try {
jaroslav@1890
   729
            Object[] elements = getArray();
jaroslav@1890
   730
            int len = elements.length;
jaroslav@1890
   731
            int added = 0;
jaroslav@1890
   732
            for (int i = 0; i < cs.length; ++i) { // scan for duplicates
jaroslav@1890
   733
                Object e = cs[i];
jaroslav@1890
   734
                if (indexOf(e, elements, 0, len) < 0 &&
jaroslav@1890
   735
                    indexOf(e, uniq, 0, added) < 0)
jaroslav@1890
   736
                    uniq[added++] = e;
jaroslav@1890
   737
            }
jaroslav@1890
   738
            if (added > 0) {
jaroslav@1890
   739
                Object[] newElements = Arrays.copyOf(elements, len + added);
jaroslav@1890
   740
                System.arraycopy(uniq, 0, newElements, len, added);
jaroslav@1890
   741
                setArray(newElements);
jaroslav@1890
   742
            }
jaroslav@1890
   743
            return added;
jaroslav@1890
   744
        } finally {
jaroslav@1890
   745
            lock.unlock();
jaroslav@1890
   746
        }
jaroslav@1890
   747
    }
jaroslav@1890
   748
jaroslav@1890
   749
    /**
jaroslav@1890
   750
     * Removes all of the elements from this list.
jaroslav@1890
   751
     * The list will be empty after this call returns.
jaroslav@1890
   752
     */
jaroslav@1890
   753
    public void clear() {
jaroslav@1890
   754
        final ReentrantLock lock = this.lock;
jaroslav@1890
   755
        lock.lock();
jaroslav@1890
   756
        try {
jaroslav@1890
   757
            setArray(new Object[0]);
jaroslav@1890
   758
        } finally {
jaroslav@1890
   759
            lock.unlock();
jaroslav@1890
   760
        }
jaroslav@1890
   761
    }
jaroslav@1890
   762
jaroslav@1890
   763
    /**
jaroslav@1890
   764
     * Appends all of the elements in the specified collection to the end
jaroslav@1890
   765
     * of this list, in the order that they are returned by the specified
jaroslav@1890
   766
     * collection's iterator.
jaroslav@1890
   767
     *
jaroslav@1890
   768
     * @param c collection containing elements to be added to this list
jaroslav@1890
   769
     * @return <tt>true</tt> if this list changed as a result of the call
jaroslav@1890
   770
     * @throws NullPointerException if the specified collection is null
jaroslav@1890
   771
     * @see #add(Object)
jaroslav@1890
   772
     */
jaroslav@1890
   773
    public boolean addAll(Collection<? extends E> c) {
jaroslav@1890
   774
        Object[] cs = c.toArray();
jaroslav@1890
   775
        if (cs.length == 0)
jaroslav@1890
   776
            return false;
jaroslav@1890
   777
        final ReentrantLock lock = this.lock;
jaroslav@1890
   778
        lock.lock();
jaroslav@1890
   779
        try {
jaroslav@1890
   780
            Object[] elements = getArray();
jaroslav@1890
   781
            int len = elements.length;
jaroslav@1890
   782
            Object[] newElements = Arrays.copyOf(elements, len + cs.length);
jaroslav@1890
   783
            System.arraycopy(cs, 0, newElements, len, cs.length);
jaroslav@1890
   784
            setArray(newElements);
jaroslav@1890
   785
            return true;
jaroslav@1890
   786
        } finally {
jaroslav@1890
   787
            lock.unlock();
jaroslav@1890
   788
        }
jaroslav@1890
   789
    }
jaroslav@1890
   790
jaroslav@1890
   791
    /**
jaroslav@1890
   792
     * Inserts all of the elements in the specified collection into this
jaroslav@1890
   793
     * list, starting at the specified position.  Shifts the element
jaroslav@1890
   794
     * currently at that position (if any) and any subsequent elements to
jaroslav@1890
   795
     * the right (increases their indices).  The new elements will appear
jaroslav@1890
   796
     * in this list in the order that they are returned by the
jaroslav@1890
   797
     * specified collection's iterator.
jaroslav@1890
   798
     *
jaroslav@1890
   799
     * @param index index at which to insert the first element
jaroslav@1890
   800
     *        from the specified collection
jaroslav@1890
   801
     * @param c collection containing elements to be added to this list
jaroslav@1890
   802
     * @return <tt>true</tt> if this list changed as a result of the call
jaroslav@1890
   803
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   804
     * @throws NullPointerException if the specified collection is null
jaroslav@1890
   805
     * @see #add(int,Object)
jaroslav@1890
   806
     */
jaroslav@1890
   807
    public boolean addAll(int index, Collection<? extends E> c) {
jaroslav@1890
   808
        Object[] cs = c.toArray();
jaroslav@1890
   809
        final ReentrantLock lock = this.lock;
jaroslav@1890
   810
        lock.lock();
jaroslav@1890
   811
        try {
jaroslav@1890
   812
            Object[] elements = getArray();
jaroslav@1890
   813
            int len = elements.length;
jaroslav@1890
   814
            if (index > len || index < 0)
jaroslav@1890
   815
                throw new IndexOutOfBoundsException("Index: "+index+
jaroslav@1890
   816
                                                    ", Size: "+len);
jaroslav@1890
   817
            if (cs.length == 0)
jaroslav@1890
   818
                return false;
jaroslav@1890
   819
            int numMoved = len - index;
jaroslav@1890
   820
            Object[] newElements;
jaroslav@1890
   821
            if (numMoved == 0)
jaroslav@1890
   822
                newElements = Arrays.copyOf(elements, len + cs.length);
jaroslav@1890
   823
            else {
jaroslav@1890
   824
                newElements = new Object[len + cs.length];
jaroslav@1890
   825
                System.arraycopy(elements, 0, newElements, 0, index);
jaroslav@1890
   826
                System.arraycopy(elements, index,
jaroslav@1890
   827
                                 newElements, index + cs.length,
jaroslav@1890
   828
                                 numMoved);
jaroslav@1890
   829
            }
jaroslav@1890
   830
            System.arraycopy(cs, 0, newElements, index, cs.length);
jaroslav@1890
   831
            setArray(newElements);
jaroslav@1890
   832
            return true;
jaroslav@1890
   833
        } finally {
jaroslav@1890
   834
            lock.unlock();
jaroslav@1890
   835
        }
jaroslav@1890
   836
    }
jaroslav@1890
   837
jaroslav@1890
   838
    /**
jaroslav@1890
   839
     * Saves the state of the list to a stream (that is, serializes it).
jaroslav@1890
   840
     *
jaroslav@1890
   841
     * @serialData The length of the array backing the list is emitted
jaroslav@1890
   842
     *               (int), followed by all of its elements (each an Object)
jaroslav@1890
   843
     *               in the proper order.
jaroslav@1890
   844
     * @param s the stream
jaroslav@1890
   845
     */
jaroslav@1890
   846
    private void writeObject(java.io.ObjectOutputStream s)
jaroslav@1890
   847
        throws java.io.IOException{
jaroslav@1890
   848
jaroslav@1890
   849
        s.defaultWriteObject();
jaroslav@1890
   850
jaroslav@1890
   851
        Object[] elements = getArray();
jaroslav@1890
   852
        // Write out array length
jaroslav@1890
   853
        s.writeInt(elements.length);
jaroslav@1890
   854
jaroslav@1890
   855
        // Write out all elements in the proper order.
jaroslav@1890
   856
        for (Object element : elements)
jaroslav@1890
   857
            s.writeObject(element);
jaroslav@1890
   858
    }
jaroslav@1890
   859
jaroslav@1890
   860
    /**
jaroslav@1890
   861
     * Reconstitutes the list from a stream (that is, deserializes it).
jaroslav@1890
   862
     *
jaroslav@1890
   863
     * @param s the stream
jaroslav@1890
   864
     */
jaroslav@1890
   865
    private void readObject(java.io.ObjectInputStream s)
jaroslav@1890
   866
        throws java.io.IOException, ClassNotFoundException {
jaroslav@1890
   867
jaroslav@1890
   868
        s.defaultReadObject();
jaroslav@1890
   869
jaroslav@1890
   870
        // bind to new lock
jaroslav@1890
   871
        resetLock();
jaroslav@1890
   872
jaroslav@1890
   873
        // Read in array length and allocate array
jaroslav@1890
   874
        int len = s.readInt();
jaroslav@1890
   875
        Object[] elements = new Object[len];
jaroslav@1890
   876
jaroslav@1890
   877
        // Read in all elements in the proper order.
jaroslav@1890
   878
        for (int i = 0; i < len; i++)
jaroslav@1890
   879
            elements[i] = s.readObject();
jaroslav@1890
   880
        setArray(elements);
jaroslav@1890
   881
    }
jaroslav@1890
   882
jaroslav@1890
   883
    /**
jaroslav@1890
   884
     * Returns a string representation of this list.  The string
jaroslav@1890
   885
     * representation consists of the string representations of the list's
jaroslav@1890
   886
     * elements in the order they are returned by its iterator, enclosed in
jaroslav@1890
   887
     * square brackets (<tt>"[]"</tt>).  Adjacent elements are separated by
jaroslav@1890
   888
     * the characters <tt>", "</tt> (comma and space).  Elements are
jaroslav@1890
   889
     * converted to strings as by {@link String#valueOf(Object)}.
jaroslav@1890
   890
     *
jaroslav@1890
   891
     * @return a string representation of this list
jaroslav@1890
   892
     */
jaroslav@1890
   893
    public String toString() {
jaroslav@1890
   894
        return Arrays.toString(getArray());
jaroslav@1890
   895
    }
jaroslav@1890
   896
jaroslav@1890
   897
    /**
jaroslav@1890
   898
     * Compares the specified object with this list for equality.
jaroslav@1890
   899
     * Returns {@code true} if the specified object is the same object
jaroslav@1890
   900
     * as this object, or if it is also a {@link List} and the sequence
jaroslav@1890
   901
     * of elements returned by an {@linkplain List#iterator() iterator}
jaroslav@1890
   902
     * over the specified list is the same as the sequence returned by
jaroslav@1890
   903
     * an iterator over this list.  The two sequences are considered to
jaroslav@1890
   904
     * be the same if they have the same length and corresponding
jaroslav@1890
   905
     * elements at the same position in the sequence are <em>equal</em>.
jaroslav@1890
   906
     * Two elements {@code e1} and {@code e2} are considered
jaroslav@1890
   907
     * <em>equal</em> if {@code (e1==null ? e2==null : e1.equals(e2))}.
jaroslav@1890
   908
     *
jaroslav@1890
   909
     * @param o the object to be compared for equality with this list
jaroslav@1890
   910
     * @return {@code true} if the specified object is equal to this list
jaroslav@1890
   911
     */
jaroslav@1890
   912
    public boolean equals(Object o) {
jaroslav@1890
   913
        if (o == this)
jaroslav@1890
   914
            return true;
jaroslav@1890
   915
        if (!(o instanceof List))
jaroslav@1890
   916
            return false;
jaroslav@1890
   917
jaroslav@1890
   918
        List<?> list = (List<?>)(o);
jaroslav@1890
   919
        Iterator<?> it = list.iterator();
jaroslav@1890
   920
        Object[] elements = getArray();
jaroslav@1890
   921
        int len = elements.length;
jaroslav@1890
   922
        for (int i = 0; i < len; ++i)
jaroslav@1890
   923
            if (!it.hasNext() || !eq(elements[i], it.next()))
jaroslav@1890
   924
                return false;
jaroslav@1890
   925
        if (it.hasNext())
jaroslav@1890
   926
            return false;
jaroslav@1890
   927
        return true;
jaroslav@1890
   928
    }
jaroslav@1890
   929
jaroslav@1890
   930
    /**
jaroslav@1890
   931
     * Returns the hash code value for this list.
jaroslav@1890
   932
     *
jaroslav@1890
   933
     * <p>This implementation uses the definition in {@link List#hashCode}.
jaroslav@1890
   934
     *
jaroslav@1890
   935
     * @return the hash code value for this list
jaroslav@1890
   936
     */
jaroslav@1890
   937
    public int hashCode() {
jaroslav@1890
   938
        int hashCode = 1;
jaroslav@1890
   939
        Object[] elements = getArray();
jaroslav@1890
   940
        int len = elements.length;
jaroslav@1890
   941
        for (int i = 0; i < len; ++i) {
jaroslav@1890
   942
            Object obj = elements[i];
jaroslav@1890
   943
            hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
jaroslav@1890
   944
        }
jaroslav@1890
   945
        return hashCode;
jaroslav@1890
   946
    }
jaroslav@1890
   947
jaroslav@1890
   948
    /**
jaroslav@1890
   949
     * Returns an iterator over the elements in this list in proper sequence.
jaroslav@1890
   950
     *
jaroslav@1890
   951
     * <p>The returned iterator provides a snapshot of the state of the list
jaroslav@1890
   952
     * when the iterator was constructed. No synchronization is needed while
jaroslav@1890
   953
     * traversing the iterator. The iterator does <em>NOT</em> support the
jaroslav@1890
   954
     * <tt>remove</tt> method.
jaroslav@1890
   955
     *
jaroslav@1890
   956
     * @return an iterator over the elements in this list in proper sequence
jaroslav@1890
   957
     */
jaroslav@1890
   958
    public Iterator<E> iterator() {
jaroslav@1890
   959
        return new COWIterator<E>(getArray(), 0);
jaroslav@1890
   960
    }
jaroslav@1890
   961
jaroslav@1890
   962
    /**
jaroslav@1890
   963
     * {@inheritDoc}
jaroslav@1890
   964
     *
jaroslav@1890
   965
     * <p>The returned iterator provides a snapshot of the state of the list
jaroslav@1890
   966
     * when the iterator was constructed. No synchronization is needed while
jaroslav@1890
   967
     * traversing the iterator. The iterator does <em>NOT</em> support the
jaroslav@1890
   968
     * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
jaroslav@1890
   969
     */
jaroslav@1890
   970
    public ListIterator<E> listIterator() {
jaroslav@1890
   971
        return new COWIterator<E>(getArray(), 0);
jaroslav@1890
   972
    }
jaroslav@1890
   973
jaroslav@1890
   974
    /**
jaroslav@1890
   975
     * {@inheritDoc}
jaroslav@1890
   976
     *
jaroslav@1890
   977
     * <p>The returned iterator provides a snapshot of the state of the list
jaroslav@1890
   978
     * when the iterator was constructed. No synchronization is needed while
jaroslav@1890
   979
     * traversing the iterator. The iterator does <em>NOT</em> support the
jaroslav@1890
   980
     * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
jaroslav@1890
   981
     *
jaroslav@1890
   982
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
   983
     */
jaroslav@1890
   984
    public ListIterator<E> listIterator(final int index) {
jaroslav@1890
   985
        Object[] elements = getArray();
jaroslav@1890
   986
        int len = elements.length;
jaroslav@1890
   987
        if (index<0 || index>len)
jaroslav@1890
   988
            throw new IndexOutOfBoundsException("Index: "+index);
jaroslav@1890
   989
jaroslav@1890
   990
        return new COWIterator<E>(elements, index);
jaroslav@1890
   991
    }
jaroslav@1890
   992
jaroslav@1890
   993
    private static class COWIterator<E> implements ListIterator<E> {
jaroslav@1890
   994
        /** Snapshot of the array */
jaroslav@1890
   995
        private final Object[] snapshot;
jaroslav@1890
   996
        /** Index of element to be returned by subsequent call to next.  */
jaroslav@1890
   997
        private int cursor;
jaroslav@1890
   998
jaroslav@1890
   999
        private COWIterator(Object[] elements, int initialCursor) {
jaroslav@1890
  1000
            cursor = initialCursor;
jaroslav@1890
  1001
            snapshot = elements;
jaroslav@1890
  1002
        }
jaroslav@1890
  1003
jaroslav@1890
  1004
        public boolean hasNext() {
jaroslav@1890
  1005
            return cursor < snapshot.length;
jaroslav@1890
  1006
        }
jaroslav@1890
  1007
jaroslav@1890
  1008
        public boolean hasPrevious() {
jaroslav@1890
  1009
            return cursor > 0;
jaroslav@1890
  1010
        }
jaroslav@1890
  1011
jaroslav@1890
  1012
        @SuppressWarnings("unchecked")
jaroslav@1890
  1013
        public E next() {
jaroslav@1890
  1014
            if (! hasNext())
jaroslav@1890
  1015
                throw new NoSuchElementException();
jaroslav@1890
  1016
            return (E) snapshot[cursor++];
jaroslav@1890
  1017
        }
jaroslav@1890
  1018
jaroslav@1890
  1019
        @SuppressWarnings("unchecked")
jaroslav@1890
  1020
        public E previous() {
jaroslav@1890
  1021
            if (! hasPrevious())
jaroslav@1890
  1022
                throw new NoSuchElementException();
jaroslav@1890
  1023
            return (E) snapshot[--cursor];
jaroslav@1890
  1024
        }
jaroslav@1890
  1025
jaroslav@1890
  1026
        public int nextIndex() {
jaroslav@1890
  1027
            return cursor;
jaroslav@1890
  1028
        }
jaroslav@1890
  1029
jaroslav@1890
  1030
        public int previousIndex() {
jaroslav@1890
  1031
            return cursor-1;
jaroslav@1890
  1032
        }
jaroslav@1890
  1033
jaroslav@1890
  1034
        /**
jaroslav@1890
  1035
         * Not supported. Always throws UnsupportedOperationException.
jaroslav@1890
  1036
         * @throws UnsupportedOperationException always; <tt>remove</tt>
jaroslav@1890
  1037
         *         is not supported by this iterator.
jaroslav@1890
  1038
         */
jaroslav@1890
  1039
        public void remove() {
jaroslav@1890
  1040
            throw new UnsupportedOperationException();
jaroslav@1890
  1041
        }
jaroslav@1890
  1042
jaroslav@1890
  1043
        /**
jaroslav@1890
  1044
         * Not supported. Always throws UnsupportedOperationException.
jaroslav@1890
  1045
         * @throws UnsupportedOperationException always; <tt>set</tt>
jaroslav@1890
  1046
         *         is not supported by this iterator.
jaroslav@1890
  1047
         */
jaroslav@1890
  1048
        public void set(E e) {
jaroslav@1890
  1049
            throw new UnsupportedOperationException();
jaroslav@1890
  1050
        }
jaroslav@1890
  1051
jaroslav@1890
  1052
        /**
jaroslav@1890
  1053
         * Not supported. Always throws UnsupportedOperationException.
jaroslav@1890
  1054
         * @throws UnsupportedOperationException always; <tt>add</tt>
jaroslav@1890
  1055
         *         is not supported by this iterator.
jaroslav@1890
  1056
         */
jaroslav@1890
  1057
        public void add(E e) {
jaroslav@1890
  1058
            throw new UnsupportedOperationException();
jaroslav@1890
  1059
        }
jaroslav@1890
  1060
    }
jaroslav@1890
  1061
jaroslav@1890
  1062
    /**
jaroslav@1890
  1063
     * Returns a view of the portion of this list between
jaroslav@1890
  1064
     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
jaroslav@1890
  1065
     * The returned list is backed by this list, so changes in the
jaroslav@1890
  1066
     * returned list are reflected in this list.
jaroslav@1890
  1067
     *
jaroslav@1890
  1068
     * <p>The semantics of the list returned by this method become
jaroslav@1890
  1069
     * undefined if the backing list (i.e., this list) is modified in
jaroslav@1890
  1070
     * any way other than via the returned list.
jaroslav@1890
  1071
     *
jaroslav@1890
  1072
     * @param fromIndex low endpoint (inclusive) of the subList
jaroslav@1890
  1073
     * @param toIndex high endpoint (exclusive) of the subList
jaroslav@1890
  1074
     * @return a view of the specified range within this list
jaroslav@1890
  1075
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@1890
  1076
     */
jaroslav@1890
  1077
    public List<E> subList(int fromIndex, int toIndex) {
jaroslav@1890
  1078
        final ReentrantLock lock = this.lock;
jaroslav@1890
  1079
        lock.lock();
jaroslav@1890
  1080
        try {
jaroslav@1890
  1081
            Object[] elements = getArray();
jaroslav@1890
  1082
            int len = elements.length;
jaroslav@1890
  1083
            if (fromIndex < 0 || toIndex > len || fromIndex > toIndex)
jaroslav@1890
  1084
                throw new IndexOutOfBoundsException();
jaroslav@1890
  1085
            return new COWSubList<E>(this, fromIndex, toIndex);
jaroslav@1890
  1086
        } finally {
jaroslav@1890
  1087
            lock.unlock();
jaroslav@1890
  1088
        }
jaroslav@1890
  1089
    }
jaroslav@1890
  1090
jaroslav@1890
  1091
    /**
jaroslav@1890
  1092
     * Sublist for CopyOnWriteArrayList.
jaroslav@1890
  1093
     * This class extends AbstractList merely for convenience, to
jaroslav@1890
  1094
     * avoid having to define addAll, etc. This doesn't hurt, but
jaroslav@1890
  1095
     * is wasteful.  This class does not need or use modCount
jaroslav@1890
  1096
     * mechanics in AbstractList, but does need to check for
jaroslav@1890
  1097
     * concurrent modification using similar mechanics.  On each
jaroslav@1890
  1098
     * operation, the array that we expect the backing list to use
jaroslav@1890
  1099
     * is checked and updated.  Since we do this for all of the
jaroslav@1890
  1100
     * base operations invoked by those defined in AbstractList,
jaroslav@1890
  1101
     * all is well.  While inefficient, this is not worth
jaroslav@1890
  1102
     * improving.  The kinds of list operations inherited from
jaroslav@1890
  1103
     * AbstractList are already so slow on COW sublists that
jaroslav@1890
  1104
     * adding a bit more space/time doesn't seem even noticeable.
jaroslav@1890
  1105
     */
jaroslav@1890
  1106
    private static class COWSubList<E>
jaroslav@1890
  1107
        extends AbstractList<E>
jaroslav@1890
  1108
        implements RandomAccess
jaroslav@1890
  1109
    {
jaroslav@1890
  1110
        private final CopyOnWriteArrayList<E> l;
jaroslav@1890
  1111
        private final int offset;
jaroslav@1890
  1112
        private int size;
jaroslav@1890
  1113
        private Object[] expectedArray;
jaroslav@1890
  1114
jaroslav@1890
  1115
        // only call this holding l's lock
jaroslav@1890
  1116
        COWSubList(CopyOnWriteArrayList<E> list,
jaroslav@1890
  1117
                   int fromIndex, int toIndex) {
jaroslav@1890
  1118
            l = list;
jaroslav@1890
  1119
            expectedArray = l.getArray();
jaroslav@1890
  1120
            offset = fromIndex;
jaroslav@1890
  1121
            size = toIndex - fromIndex;
jaroslav@1890
  1122
        }
jaroslav@1890
  1123
jaroslav@1890
  1124
        // only call this holding l's lock
jaroslav@1890
  1125
        private void checkForComodification() {
jaroslav@1890
  1126
            if (l.getArray() != expectedArray)
jaroslav@1890
  1127
                throw new ConcurrentModificationException();
jaroslav@1890
  1128
        }
jaroslav@1890
  1129
jaroslav@1890
  1130
        // only call this holding l's lock
jaroslav@1890
  1131
        private void rangeCheck(int index) {
jaroslav@1890
  1132
            if (index<0 || index>=size)
jaroslav@1890
  1133
                throw new IndexOutOfBoundsException("Index: "+index+
jaroslav@1890
  1134
                                                    ",Size: "+size);
jaroslav@1890
  1135
        }
jaroslav@1890
  1136
jaroslav@1890
  1137
        public E set(int index, E element) {
jaroslav@1890
  1138
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1139
            lock.lock();
jaroslav@1890
  1140
            try {
jaroslav@1890
  1141
                rangeCheck(index);
jaroslav@1890
  1142
                checkForComodification();
jaroslav@1890
  1143
                E x = l.set(index+offset, element);
jaroslav@1890
  1144
                expectedArray = l.getArray();
jaroslav@1890
  1145
                return x;
jaroslav@1890
  1146
            } finally {
jaroslav@1890
  1147
                lock.unlock();
jaroslav@1890
  1148
            }
jaroslav@1890
  1149
        }
jaroslav@1890
  1150
jaroslav@1890
  1151
        public E get(int index) {
jaroslav@1890
  1152
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1153
            lock.lock();
jaroslav@1890
  1154
            try {
jaroslav@1890
  1155
                rangeCheck(index);
jaroslav@1890
  1156
                checkForComodification();
jaroslav@1890
  1157
                return l.get(index+offset);
jaroslav@1890
  1158
            } finally {
jaroslav@1890
  1159
                lock.unlock();
jaroslav@1890
  1160
            }
jaroslav@1890
  1161
        }
jaroslav@1890
  1162
jaroslav@1890
  1163
        public int size() {
jaroslav@1890
  1164
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1165
            lock.lock();
jaroslav@1890
  1166
            try {
jaroslav@1890
  1167
                checkForComodification();
jaroslav@1890
  1168
                return size;
jaroslav@1890
  1169
            } finally {
jaroslav@1890
  1170
                lock.unlock();
jaroslav@1890
  1171
            }
jaroslav@1890
  1172
        }
jaroslav@1890
  1173
jaroslav@1890
  1174
        public void add(int index, E element) {
jaroslav@1890
  1175
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1176
            lock.lock();
jaroslav@1890
  1177
            try {
jaroslav@1890
  1178
                checkForComodification();
jaroslav@1890
  1179
                if (index<0 || index>size)
jaroslav@1890
  1180
                    throw new IndexOutOfBoundsException();
jaroslav@1890
  1181
                l.add(index+offset, element);
jaroslav@1890
  1182
                expectedArray = l.getArray();
jaroslav@1890
  1183
                size++;
jaroslav@1890
  1184
            } finally {
jaroslav@1890
  1185
                lock.unlock();
jaroslav@1890
  1186
            }
jaroslav@1890
  1187
        }
jaroslav@1890
  1188
jaroslav@1890
  1189
        public void clear() {
jaroslav@1890
  1190
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1191
            lock.lock();
jaroslav@1890
  1192
            try {
jaroslav@1890
  1193
                checkForComodification();
jaroslav@1890
  1194
                l.removeRange(offset, offset+size);
jaroslav@1890
  1195
                expectedArray = l.getArray();
jaroslav@1890
  1196
                size = 0;
jaroslav@1890
  1197
            } finally {
jaroslav@1890
  1198
                lock.unlock();
jaroslav@1890
  1199
            }
jaroslav@1890
  1200
        }
jaroslav@1890
  1201
jaroslav@1890
  1202
        public E remove(int index) {
jaroslav@1890
  1203
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1204
            lock.lock();
jaroslav@1890
  1205
            try {
jaroslav@1890
  1206
                rangeCheck(index);
jaroslav@1890
  1207
                checkForComodification();
jaroslav@1890
  1208
                E result = l.remove(index+offset);
jaroslav@1890
  1209
                expectedArray = l.getArray();
jaroslav@1890
  1210
                size--;
jaroslav@1890
  1211
                return result;
jaroslav@1890
  1212
            } finally {
jaroslav@1890
  1213
                lock.unlock();
jaroslav@1890
  1214
            }
jaroslav@1890
  1215
        }
jaroslav@1890
  1216
jaroslav@1890
  1217
        public boolean remove(Object o) {
jaroslav@1890
  1218
            int index = indexOf(o);
jaroslav@1890
  1219
            if (index == -1)
jaroslav@1890
  1220
                return false;
jaroslav@1890
  1221
            remove(index);
jaroslav@1890
  1222
            return true;
jaroslav@1890
  1223
        }
jaroslav@1890
  1224
jaroslav@1890
  1225
        public Iterator<E> iterator() {
jaroslav@1890
  1226
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1227
            lock.lock();
jaroslav@1890
  1228
            try {
jaroslav@1890
  1229
                checkForComodification();
jaroslav@1890
  1230
                return new COWSubListIterator<E>(l, 0, offset, size);
jaroslav@1890
  1231
            } finally {
jaroslav@1890
  1232
                lock.unlock();
jaroslav@1890
  1233
            }
jaroslav@1890
  1234
        }
jaroslav@1890
  1235
jaroslav@1890
  1236
        public ListIterator<E> listIterator(final int index) {
jaroslav@1890
  1237
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1238
            lock.lock();
jaroslav@1890
  1239
            try {
jaroslav@1890
  1240
                checkForComodification();
jaroslav@1890
  1241
                if (index<0 || index>size)
jaroslav@1890
  1242
                    throw new IndexOutOfBoundsException("Index: "+index+
jaroslav@1890
  1243
                                                        ", Size: "+size);
jaroslav@1890
  1244
                return new COWSubListIterator<E>(l, index, offset, size);
jaroslav@1890
  1245
            } finally {
jaroslav@1890
  1246
                lock.unlock();
jaroslav@1890
  1247
            }
jaroslav@1890
  1248
        }
jaroslav@1890
  1249
jaroslav@1890
  1250
        public List<E> subList(int fromIndex, int toIndex) {
jaroslav@1890
  1251
            final ReentrantLock lock = l.lock;
jaroslav@1890
  1252
            lock.lock();
jaroslav@1890
  1253
            try {
jaroslav@1890
  1254
                checkForComodification();
jaroslav@1890
  1255
                if (fromIndex<0 || toIndex>size)
jaroslav@1890
  1256
                    throw new IndexOutOfBoundsException();
jaroslav@1890
  1257
                return new COWSubList<E>(l, fromIndex + offset,
jaroslav@1890
  1258
                                         toIndex + offset);
jaroslav@1890
  1259
            } finally {
jaroslav@1890
  1260
                lock.unlock();
jaroslav@1890
  1261
            }
jaroslav@1890
  1262
        }
jaroslav@1890
  1263
jaroslav@1890
  1264
    }
jaroslav@1890
  1265
jaroslav@1890
  1266
jaroslav@1890
  1267
    private static class COWSubListIterator<E> implements ListIterator<E> {
jaroslav@1890
  1268
        private final ListIterator<E> i;
jaroslav@1890
  1269
        private final int index;
jaroslav@1890
  1270
        private final int offset;
jaroslav@1890
  1271
        private final int size;
jaroslav@1890
  1272
jaroslav@1890
  1273
        COWSubListIterator(List<E> l, int index, int offset,
jaroslav@1890
  1274
                           int size) {
jaroslav@1890
  1275
            this.index = index;
jaroslav@1890
  1276
            this.offset = offset;
jaroslav@1890
  1277
            this.size = size;
jaroslav@1890
  1278
            i = l.listIterator(index+offset);
jaroslav@1890
  1279
        }
jaroslav@1890
  1280
jaroslav@1890
  1281
        public boolean hasNext() {
jaroslav@1890
  1282
            return nextIndex() < size;
jaroslav@1890
  1283
        }
jaroslav@1890
  1284
jaroslav@1890
  1285
        public E next() {
jaroslav@1890
  1286
            if (hasNext())
jaroslav@1890
  1287
                return i.next();
jaroslav@1890
  1288
            else
jaroslav@1890
  1289
                throw new NoSuchElementException();
jaroslav@1890
  1290
        }
jaroslav@1890
  1291
jaroslav@1890
  1292
        public boolean hasPrevious() {
jaroslav@1890
  1293
            return previousIndex() >= 0;
jaroslav@1890
  1294
        }
jaroslav@1890
  1295
jaroslav@1890
  1296
        public E previous() {
jaroslav@1890
  1297
            if (hasPrevious())
jaroslav@1890
  1298
                return i.previous();
jaroslav@1890
  1299
            else
jaroslav@1890
  1300
                throw new NoSuchElementException();
jaroslav@1890
  1301
        }
jaroslav@1890
  1302
jaroslav@1890
  1303
        public int nextIndex() {
jaroslav@1890
  1304
            return i.nextIndex() - offset;
jaroslav@1890
  1305
        }
jaroslav@1890
  1306
jaroslav@1890
  1307
        public int previousIndex() {
jaroslav@1890
  1308
            return i.previousIndex() - offset;
jaroslav@1890
  1309
        }
jaroslav@1890
  1310
jaroslav@1890
  1311
        public void remove() {
jaroslav@1890
  1312
            throw new UnsupportedOperationException();
jaroslav@1890
  1313
        }
jaroslav@1890
  1314
jaroslav@1890
  1315
        public void set(E e) {
jaroslav@1890
  1316
            throw new UnsupportedOperationException();
jaroslav@1890
  1317
        }
jaroslav@1890
  1318
jaroslav@1890
  1319
        public void add(E e) {
jaroslav@1890
  1320
            throw new UnsupportedOperationException();
jaroslav@1890
  1321
        }
jaroslav@1890
  1322
    }
jaroslav@1890
  1323
jaroslav@1890
  1324
    // Support for resetting lock while deserializing
jaroslav@1890
  1325
    private void resetLock() {
jaroslav@1890
  1326
        UNSAFE.putObjectVolatile(this, lockOffset, new ReentrantLock());
jaroslav@1890
  1327
    }
jaroslav@1890
  1328
    private static final sun.misc.Unsafe UNSAFE;
jaroslav@1890
  1329
    private static final long lockOffset;
jaroslav@1890
  1330
    static {
jaroslav@1890
  1331
        try {
jaroslav@1890
  1332
            UNSAFE = sun.misc.Unsafe.getUnsafe();
jaroslav@1890
  1333
            Class k = CopyOnWriteArrayList.class;
jaroslav@1890
  1334
            lockOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  1335
                (k.getDeclaredField("lock"));
jaroslav@1890
  1336
        } catch (Exception e) {
jaroslav@1890
  1337
            throw new Error(e);
jaroslav@1890
  1338
        }
jaroslav@1890
  1339
    }
jaroslav@1890
  1340
}