1 7 8 package java.util.concurrent.atomic; 9 import sun.misc.Unsafe; 10 import java.util.*; 11 12 21 public class AtomicReferenceArray<E> implements java.io.Serializable { 22 private static final long serialVersionUID = -6209656149925076980L; 23 24 private static final Unsafe unsafe = Unsafe.getUnsafe(); 25 private static final int base = unsafe.arrayBaseOffset(Object [].class); 26 private static final int scale = unsafe.arrayIndexScale(Object [].class); 27 private final Object [] array; 28 29 private long rawIndex(int i) { 30 if (i < 0 || i >= array.length) 31 throw new IndexOutOfBoundsException ("index " + i); 32 return base + i * scale; 33 } 34 35 39 public AtomicReferenceArray(int length) { 40 array = new Object [length]; 41 if (length > 0) 43 unsafe.putObjectVolatile(array, rawIndex(0), null); 44 } 45 46 53 public AtomicReferenceArray(E[] array) { 54 if (array == null) 55 throw new NullPointerException (); 56 int length = array.length; 57 this.array = new Object [length]; 58 if (length > 0) { 59 int last = length-1; 60 for (int i = 0; i < last; ++i) 61 this.array[i] = array[i]; 62 E e = array[last]; 64 unsafe.putObjectVolatile(this.array, rawIndex(last), e); 65 } 66 } 67 68 73 public final int length() { 74 return array.length; 75 } 76 77 83 public final E get(int i) { 84 return (E) unsafe.getObjectVolatile(array, rawIndex(i)); 85 } 86 87 93 public final void set(int i, E newValue) { 94 unsafe.putObjectVolatile(array, rawIndex(i), newValue); 95 } 96 97 105 public final E getAndSet(int i, E newValue) { 106 while (true) { 107 E current = get(i); 108 if (compareAndSet(i, current, newValue)) 109 return current; 110 } 111 } 112 113 122 public final boolean compareAndSet(int i, E expect, E update) { 123 return unsafe.compareAndSwapObject(array, rawIndex(i), 124 expect, update); 125 } 126 127 136 public final boolean weakCompareAndSet(int i, E expect, E update) { 137 return compareAndSet(i, expect, update); 138 } 139 140 144 public String toString() { 145 if (array.length > 0) get(0); 147 return Arrays.toString(array); 148 } 149 150 } 151 | Popular Tags |