1 7 8 package java.util.concurrent.atomic; 9 import sun.misc.Unsafe; 10 11 19 public class AtomicReference<V> implements java.io.Serializable { 20 private static final long serialVersionUID = -1848883965231344442L; 21 22 private static final Unsafe unsafe = Unsafe.getUnsafe(); 23 private static final long valueOffset; 24 25 static { 26 try { 27 valueOffset = unsafe.objectFieldOffset 28 (AtomicReference .class.getDeclaredField("value")); 29 } catch(Exception ex) { throw new Error (ex); } 30 } 31 32 private volatile V value; 33 34 39 public AtomicReference(V initialValue) { 40 value = initialValue; 41 } 42 43 46 public AtomicReference() { 47 } 48 49 54 public final V get() { 55 return value; 56 } 57 58 63 public final void set(V newValue) { 64 value = newValue; 65 } 66 67 75 public final boolean compareAndSet(V expect, V update) { 76 return unsafe.compareAndSwapObject(this, valueOffset, expect, update); 77 } 78 79 87 public final boolean weakCompareAndSet(V expect, V update) { 88 return unsafe.compareAndSwapObject(this, valueOffset, expect, update); 89 } 90 91 97 public final V getAndSet(V newValue) { 98 while (true) { 99 V x = get(); 100 if (compareAndSet(x, newValue)) 101 return x; 102 } 103 } 104 105 109 public String toString() { 110 return String.valueOf(get()); 111 } 112 113 } 114 | Popular Tags |