1/*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7package java.util.concurrent.atomic;
8
9import java.util.Arrays;
10import java.lang.reflect.Array;
11import sun.misc.Unsafe;
12
13/**
14 * An array of object references in which elements may be updated
15 * atomically.  See the {@link java.util.concurrent.atomic} package
16 * specification for description of the properties of atomic
17 * variables.
18 * @since 1.5
19 * @author Doug Lea
20 * @param <E> The base class of elements held in this array
21 */
22public class AtomicReferenceArray<E> implements java.io.Serializable {
23    private static final long serialVersionUID = -6209656149925076980L;
24
25    private static final Unsafe unsafe;
26    private static final int base;
27    private static final int shift;
28    private static final long arrayFieldOffset;
29    private final Object[] array; // must have exact type Object[]
30
31    static {
32        int scale;
33        try {
34            unsafe = Unsafe.getUnsafe();
35            arrayFieldOffset = unsafe.objectFieldOffset
36                (AtomicReferenceArray.class.getDeclaredField("array"));
37            base = unsafe.arrayBaseOffset(Object[].class);
38            scale = unsafe.arrayIndexScale(Object[].class);
39        } catch (Exception e) {
40            throw new Error(e);
41        }
42        if ((scale & (scale - 1)) != 0)
43            throw new Error("data type scale not a power of two");
44        shift = 31 - Integer.numberOfLeadingZeros(scale);
45    }
46
47    private long checkedByteOffset(int i) {
48        if (i < 0 || i >= array.length)
49            throw new IndexOutOfBoundsException("index " + i);
50
51        return byteOffset(i);
52    }
53
54    private static long byteOffset(int i) {
55        return ((long) i << shift) + base;
56    }
57
58    /**
59     * Creates a new AtomicReferenceArray of the given length, with all
60     * elements initially null.
61     *
62     * @param length the length of the array
63     */
64    public AtomicReferenceArray(int length) {
65        array = new Object[length];
66    }
67
68    /**
69     * Creates a new AtomicReferenceArray with the same length as, and
70     * all elements copied from, the given array.
71     *
72     * @param array the array to copy elements from
73     * @throws NullPointerException if array is null
74     */
75    public AtomicReferenceArray(E[] array) {
76        // Visibility guaranteed by final field guarantees
77        this.array = Arrays.copyOf(array, array.length, Object[].class);
78    }
79
80    /**
81     * Returns the length of the array.
82     *
83     * @return the length of the array
84     */
85    public final int length() {
86        return array.length;
87    }
88
89    /**
90     * Gets the current value at position {@code i}.
91     *
92     * @param i the index
93     * @return the current value
94     */
95    public final E get(int i) {
96        return getRaw(checkedByteOffset(i));
97    }
98
99    private E getRaw(long offset) {
100        return (E) unsafe.getObjectVolatile(array, offset);
101    }
102
103    /**
104     * Sets the element at position {@code i} to the given value.
105     *
106     * @param i the index
107     * @param newValue the new value
108     */
109    public final void set(int i, E newValue) {
110        unsafe.putObjectVolatile(array, checkedByteOffset(i), newValue);
111    }
112
113    /**
114     * Eventually sets the element at position {@code i} to the given value.
115     *
116     * @param i the index
117     * @param newValue the new value
118     * @since 1.6
119     */
120    public final void lazySet(int i, E newValue) {
121        unsafe.putOrderedObject(array, checkedByteOffset(i), newValue);
122    }
123
124
125    /**
126     * Atomically sets the element at position {@code i} to the given
127     * value and returns the old value.
128     *
129     * @param i the index
130     * @param newValue the new value
131     * @return the previous value
132     */
133    public final E getAndSet(int i, E newValue) {
134        long offset = checkedByteOffset(i);
135        while (true) {
136            E current = getRaw(offset);
137            if (compareAndSetRaw(offset, current, newValue))
138                return current;
139        }
140    }
141
142    /**
143     * Atomically sets the element at position {@code i} to the given
144     * updated value if the current value {@code ==} the expected value.
145     *
146     * @param i the index
147     * @param expect the expected value
148     * @param update the new value
149     * @return true if successful. False return indicates that
150     * the actual value was not equal to the expected value.
151     */
152    public final boolean compareAndSet(int i, E expect, E update) {
153        return compareAndSetRaw(checkedByteOffset(i), expect, update);
154    }
155
156    private boolean compareAndSetRaw(long offset, E expect, E update) {
157        return unsafe.compareAndSwapObject(array, offset, expect, update);
158    }
159
160    /**
161     * Atomically sets the element at position {@code i} to the given
162     * updated value if the current value {@code ==} the expected value.
163     *
164     * <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
165     * and does not provide ordering guarantees, so is only rarely an
166     * appropriate alternative to {@code compareAndSet}.
167     *
168     * @param i the index
169     * @param expect the expected value
170     * @param update the new value
171     * @return true if successful.
172     */
173    public final boolean weakCompareAndSet(int i, E expect, E update) {
174        return compareAndSet(i, expect, update);
175    }
176
177    /**
178     * Returns the String representation of the current values of array.
179     * @return the String representation of the current values of array
180     */
181    public String toString() {
182        int iMax = array.length - 1;
183        if (iMax == -1)
184            return "[]";
185
186        StringBuilder b = new StringBuilder();
187        b.append('[');
188        for (int i = 0; ; i++) {
189            b.append(getRaw(byteOffset(i)));
190            if (i == iMax)
191                return b.append(']').toString();
192            b.append(',').append(' ');
193        }
194    }
195
196    /**
197     * Reconstitutes the instance from a stream (that is, deserializes it).
198     * @param s the stream
199     */
200    private void readObject(java.io.ObjectInputStream s)
201        throws java.io.IOException, ClassNotFoundException,
202        java.io.InvalidObjectException {
203        // Note: This must be changed if any additional fields are defined
204        Object a = s.readFields().get("array", null);
205        if (a == null || !a.getClass().isArray())
206            throw new java.io.InvalidObjectException("Not array type");
207        if (a.getClass() != Object[].class)
208            a = Arrays.copyOf((Object[])a, Array.getLength(a), Object[].class);
209        unsafe.putObjectVolatile(this, arrayFieldOffset, a);
210    }
211
212}
213