1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent.atomic; 37 38 import java.util.Arrays; 39 import java.util.function.UnaryOperator; 40 import java.util.function.BinaryOperator; 41 import java.lang.reflect.Array; 42 import sun.misc.Unsafe; 43 44 /** 45 * An array of object references in which elements may be updated 46 * atomically. See the {@link java.util.concurrent.atomic} package 47 * specification for description of the properties of atomic 48 * variables. 49 * @since 1.5 50 * @author Doug Lea 51 * @param <E> The base class of elements held in this array 52 */ 53 public class AtomicReferenceArray<E> implements java.io.Serializable { 54 private static final long serialVersionUID = -6209656149925076980L; 55 56 private static final Unsafe unsafe; 57 private static final int base; 58 private static final int shift; 59 private static final long arrayFieldOffset; 60 private final Object[] array; // must have exact type Object[] 61 62 static { 63 int scale; 64 try { 65 unsafe = Unsafe.getUnsafe(); 66 arrayFieldOffset = unsafe.objectFieldOffset 67 (AtomicReferenceArray.class.getDeclaredField("array")); 68 base = unsafe.arrayBaseOffset(Object[].class); 69 scale = unsafe.arrayIndexScale(Object[].class); 70 } catch (Exception e) { 71 throw new Error(e); 72 } 73 if ((scale & (scale - 1)) != 0) 74 throw new Error("data type scale not a power of two"); 75 shift = 31 - Integer.numberOfLeadingZeros(scale); 76 } 77 78 private long checkedByteOffset(int i) { 79 if (i < 0 || i >= array.length) 80 throw new IndexOutOfBoundsException("index " + i); 81 82 return byteOffset(i); 83 } 84 85 private static long byteOffset(int i) { 86 return ((long) i << shift) + base; 87 } 88 89 /** 90 * Creates a new AtomicReferenceArray of the given length, with all 91 * elements initially null. 92 * 93 * @param length the length of the array 94 */ 95 public AtomicReferenceArray(int length) { 96 array = new Object[length]; 97 } 98 99 /** 100 * Creates a new AtomicReferenceArray with the same length as, and 101 * all elements copied from, the given array. 102 * 103 * @param array the array to copy elements from 104 * @throws NullPointerException if array is null 105 */ 106 public AtomicReferenceArray(E[] array) { 107 // Visibility guaranteed by final field guarantees 108 this.array = Arrays.copyOf(array, array.length, Object[].class); 109 } 110 111 /** 112 * Returns the length of the array. 113 * 114 * @return the length of the array 115 */ 116 public final int length() { 117 return array.length; 118 } 119 120 /** 121 * Gets the current value at position {@code i}. 122 * 123 * @param i the index 124 * @return the current value 125 */ 126 public final E get(int i) { 127 return getRaw(checkedByteOffset(i)); 128 } 129 130 @SuppressWarnings("unchecked") 131 private E getRaw(long offset) { 132 return (E) unsafe.getObjectVolatile(array, offset); 133 } 134 135 /** 136 * Sets the element at position {@code i} to the given value. 137 * 138 * @param i the index 139 * @param newValue the new value 140 */ 141 public final void set(int i, E newValue) { 142 unsafe.putObjectVolatile(array, checkedByteOffset(i), newValue); 143 } 144 145 /** 146 * Eventually sets the element at position {@code i} to the given value. 147 * 148 * @param i the index 149 * @param newValue the new value 150 * @since 1.6 151 */ 152 public final void lazySet(int i, E newValue) { 153 unsafe.putOrderedObject(array, checkedByteOffset(i), newValue); 154 } 155 156 /** 157 * Atomically sets the element at position {@code i} to the given 158 * value and returns the old value. 159 * 160 * @param i the index 161 * @param newValue the new value 162 * @return the previous value 163 */ 164 @SuppressWarnings("unchecked") 165 public final E getAndSet(int i, E newValue) { 166 return (E)unsafe.getAndSetObject(array, checkedByteOffset(i), newValue); 167 } 168 169 /** 170 * Atomically sets the element at position {@code i} to the given 171 * updated value if the current value {@code ==} the expected value. 172 * 173 * @param i the index 174 * @param expect the expected value 175 * @param update the new value 176 * @return true if successful. False return indicates that 177 * the actual value was not equal to the expected value. 178 */ 179 public final boolean compareAndSet(int i, E expect, E update) { 180 return compareAndSetRaw(checkedByteOffset(i), expect, update); 181 } 182 183 private boolean compareAndSetRaw(long offset, E expect, E update) { 184 return unsafe.compareAndSwapObject(array, offset, expect, update); 185 } 186 187 /** 188 * Atomically sets the element at position {@code i} to the given 189 * updated value if the current value {@code ==} the expected value. 190 * 191 * <p>May <a href="package-summary.html#Spurious">fail spuriously</a> 192 * and does not provide ordering guarantees, so is only rarely an 193 * appropriate alternative to {@code compareAndSet}. 194 * 195 * @param i the index 196 * @param expect the expected value 197 * @param update the new value 198 * @return true if successful 199 */ 200 public final boolean weakCompareAndSet(int i, E expect, E update) { 201 return compareAndSet(i, expect, update); 202 } 203 204 /** 205 * Atomically updates the element at index {@code i} with the results 206 * of applying the given function. The function should be 207 * side-effect-free, since it may be re-applied when attempted 208 * updates fail due to contention among threads. 209 * 210 * @param i the index 211 * @param updateFunction a side-effect-free function 212 * @return the previous value 213 * @since 1.8 214 */ 215 public final E getAndUpdate(int i, UnaryOperator<E> updateFunction) { 216 long offset = checkedByteOffset(i); 217 E prev, next; 218 do { 219 prev = getRaw(offset); 220 next = updateFunction.operate(prev); 221 } while (!compareAndSetRaw(offset, prev, next)); 222 return prev; 223 } 224 225 /** 226 * Atomically updates the element at index {@code i} with the results 227 * of applying the given function. The function should be 228 * side-effect-free, since it may be re-applied when attempted 229 * updates fail due to contention among threads. 230 * 231 * @param i the index 232 * @param updateFunction a side-effect-free function 233 * @return the updated value 234 * @since 1.8 235 */ 236 public final E updateAndGet(int i, UnaryOperator<E> updateFunction) { 237 long offset = checkedByteOffset(i); 238 E prev, next; 239 do { 240 prev = getRaw(offset); 241 next = updateFunction.operate(prev); 242 } while (!compareAndSetRaw(offset, prev, next)); 243 return next; 244 } 245 246 /** 247 * Atomically updates the element at index {@code i} with the results 248 * of applying the given function to the current and given values. 249 * The function should be side-effect-free, since it may be 250 * re-applied when attempted updates fail due to contention among 251 * threads. The function is applied with the current value at index 252 * {@code i} as its first argument, and the given update as the second 253 * argument. 254 * 255 * @param i the index 256 * @param x the update value 257 * @param accumulatorFunction a side-effect-free function of two arguments 258 * @return the previous value 259 * @since 1.8 260 */ 261 public final E getAndAccumulate(int i, E x, 262 BinaryOperator<E> accumulatorFunction) { 263 long offset = checkedByteOffset(i); 264 E prev, next; 265 do { 266 prev = getRaw(offset); 267 next = accumulatorFunction.operate(prev, x); 268 } while (!compareAndSetRaw(offset, prev, next)); 269 return prev; 270 } 271 272 /** 273 * Atomically updates the element at index {@code i} with the results 274 * of applying the given function to the current and given values. 275 * The function should be side-effect-free, since it may be 276 * re-applied when attempted updates fail due to contention among 277 * threads. The function is applied with the current value at index 278 * {@code i} as its first argument, and the given update as the second 279 * argument. 280 * 281 * @param i the index 282 * @param x the update value 283 * @param accumulatorFunction a side-effect-free function of two arguments 284 * @return the updated value 285 * @since 1.8 286 */ 287 public final E accumulateAndGet(int i, E x, 288 BinaryOperator<E> accumulatorFunction) { 289 long offset = checkedByteOffset(i); 290 E prev, next; 291 do { 292 prev = getRaw(offset); 293 next = accumulatorFunction.operate(prev, x); 294 } while (!compareAndSetRaw(offset, prev, next)); 295 return next; 296 } 297 298 /** 299 * Returns the String representation of the current values of array. 300 * @return the String representation of the current values of array 301 */ 302 public String toString() { 303 int iMax = array.length - 1; 304 if (iMax == -1) 305 return "[]"; 306 307 StringBuilder b = new StringBuilder(); 308 b.append('['); 309 for (int i = 0; ; i++) { 310 b.append(getRaw(byteOffset(i))); 311 if (i == iMax) 312 return b.append(']').toString(); 313 b.append(',').append(' '); 314 } 315 } 316 317 /** 318 * Reconstitutes the instance from a stream (that is, deserializes it). 319 */ 320 private void readObject(java.io.ObjectInputStream s) 321 throws java.io.IOException, ClassNotFoundException, 322 java.io.InvalidObjectException { 323 // Note: This must be changed if any additional fields are defined 324 Object a = s.readFields().get("array", null); 325 if (a == null || !a.getClass().isArray()) 326 throw new java.io.InvalidObjectException("Not array type"); 327 if (a.getClass() != Object[].class) 328 a = Arrays.copyOf((Object[])a, Array.getLength(a), Object[].class); 329 unsafe.putObjectVolatile(this, arrayFieldOffset, a); 330 } 331 332 }