1 7 8 package java.util.concurrent.atomic; 9 import sun.misc.Unsafe; 10 11 22 public class AtomicBoolean implements java.io.Serializable { 23 private static final long serialVersionUID = 4654671469794556979L; 24 private static final Unsafe unsafe = Unsafe.getUnsafe(); 26 private static final long valueOffset; 27 28 static { 29 try { 30 valueOffset = unsafe.objectFieldOffset 31 (AtomicBoolean .class.getDeclaredField("value")); 32 } catch (Exception ex) { throw new Error (ex); } 33 } 34 35 private volatile int value; 36 37 42 public AtomicBoolean(boolean initialValue) { 43 value = initialValue ? 1 : 0; 44 } 45 46 49 public AtomicBoolean() { 50 } 51 52 57 public final boolean get() { 58 return value != 0; 59 } 60 61 69 public final boolean compareAndSet(boolean expect, boolean update) { 70 int e = expect ? 1 : 0; 71 int u = update ? 1 : 0; 72 return unsafe.compareAndSwapInt(this, valueOffset, e, u); 73 } 74 75 83 public boolean weakCompareAndSet(boolean expect, boolean update) { 84 int e = expect ? 1 : 0; 85 int u = update ? 1 : 0; 86 return unsafe.compareAndSwapInt(this, valueOffset, e, u); 87 } 88 89 94 public final void set(boolean newValue) { 95 value = newValue ? 1 : 0; 96 } 97 98 104 public final boolean getAndSet(boolean newValue) { 105 for (;;) { 106 boolean current = get(); 107 if (compareAndSet(current, newValue)) 108 return current; 109 } 110 } 111 112 116 public String toString() { 117 return Boolean.toString(get()); 118 } 119 120 } 121 | Popular Tags |