1 7 8 package java.util.concurrent.atomic; 9 import sun.misc.Unsafe; 10 11 24 public class AtomicLong extends Number implements java.io.Serializable { 25 private static final long serialVersionUID = 1927816293512124184L; 26 27 private static final Unsafe unsafe = Unsafe.getUnsafe(); 29 private static final long valueOffset; 30 31 37 static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8(); 38 39 43 private static native boolean VMSupportsCS8(); 44 45 static { 46 try { 47 valueOffset = unsafe.objectFieldOffset 48 (AtomicLong .class.getDeclaredField("value")); 49 } catch(Exception ex) { throw new Error (ex); } 50 } 51 52 private volatile long value; 53 54 59 public AtomicLong(long initialValue) { 60 value = initialValue; 61 } 62 63 66 public AtomicLong() { 67 } 68 69 74 public final long get() { 75 return value; 76 } 77 78 83 public final void set(long newValue) { 84 value = newValue; 85 } 86 87 93 public final long getAndSet(long newValue) { 94 while (true) { 95 long current = get(); 96 if (compareAndSet(current, newValue)) 97 return current; 98 } 99 } 100 101 109 public final boolean compareAndSet(long expect, long update) { 110 return unsafe.compareAndSwapLong(this, valueOffset, expect, update); 111 } 112 113 121 public final boolean weakCompareAndSet(long expect, long update) { 122 return unsafe.compareAndSwapLong(this, valueOffset, expect, update); 123 } 124 125 129 public final long getAndIncrement() { 130 while (true) { 131 long current = get(); 132 long next = current + 1; 133 if (compareAndSet(current, next)) 134 return current; 135 } 136 } 137 138 139 143 public final long getAndDecrement() { 144 while (true) { 145 long current = get(); 146 long next = current - 1; 147 if (compareAndSet(current, next)) 148 return current; 149 } 150 } 151 152 153 158 public final long getAndAdd(long delta) { 159 while (true) { 160 long current = get(); 161 long next = current + delta; 162 if (compareAndSet(current, next)) 163 return current; 164 } 165 } 166 167 171 public final long incrementAndGet() { 172 for (;;) { 173 long current = get(); 174 long next = current + 1; 175 if (compareAndSet(current, next)) 176 return next; 177 } 178 } 179 180 184 public final long decrementAndGet() { 185 for (;;) { 186 long current = get(); 187 long next = current - 1; 188 if (compareAndSet(current, next)) 189 return next; 190 } 191 } 192 193 194 199 public final long addAndGet(long delta) { 200 for (;;) { 201 long current = get(); 202 long next = current + delta; 203 if (compareAndSet(current, next)) 204 return next; 205 } 206 } 207 208 212 public String toString() { 213 return Long.toString(get()); 214 } 215 216 217 public int intValue() { 218 return (int)get(); 219 } 220 221 public long longValue() { 222 return (long)get(); 223 } 224 225 public float floatValue() { 226 return (float)get(); 227 } 228 229 public double doubleValue() { 230 return (double)get(); 231 } 232 233 } 234 | Popular Tags |