1 7 8 package java.util.concurrent.atomic; 9 import sun.misc.Unsafe; 10 11 25 public class AtomicInteger extends Number implements java.io.Serializable { 26 private static final long serialVersionUID = 6214790243416807050L; 27 28 private static final Unsafe unsafe = Unsafe.getUnsafe(); 30 private static final long valueOffset; 31 32 static { 33 try { 34 valueOffset = unsafe.objectFieldOffset 35 (AtomicInteger .class.getDeclaredField("value")); 36 } catch(Exception ex) { throw new Error (ex); } 37 } 38 39 private volatile int value; 40 41 46 public AtomicInteger(int initialValue) { 47 value = initialValue; 48 } 49 50 53 public AtomicInteger() { 54 } 55 56 61 public final int get() { 62 return value; 63 } 64 65 70 public final void set(int newValue) { 71 value = newValue; 72 } 73 74 80 public final int getAndSet(int newValue) { 81 for (;;) { 82 int current = get(); 83 if (compareAndSet(current, newValue)) 84 return current; 85 } 86 } 87 88 89 97 public final boolean compareAndSet(int expect, int update) { 98 return unsafe.compareAndSwapInt(this, valueOffset, expect, update); 99 } 100 101 109 public final boolean weakCompareAndSet(int expect, int update) { 110 return unsafe.compareAndSwapInt(this, valueOffset, expect, update); 111 } 112 113 114 118 public final int getAndIncrement() { 119 for (;;) { 120 int current = get(); 121 int next = current + 1; 122 if (compareAndSet(current, next)) 123 return current; 124 } 125 } 126 127 128 132 public final int getAndDecrement() { 133 for (;;) { 134 int current = get(); 135 int next = current - 1; 136 if (compareAndSet(current, next)) 137 return current; 138 } 139 } 140 141 142 147 public final int getAndAdd(int delta) { 148 for (;;) { 149 int current = get(); 150 int next = current + delta; 151 if (compareAndSet(current, next)) 152 return current; 153 } 154 } 155 156 160 public final int incrementAndGet() { 161 for (;;) { 162 int current = get(); 163 int next = current + 1; 164 if (compareAndSet(current, next)) 165 return next; 166 } 167 } 168 169 173 public final int decrementAndGet() { 174 for (;;) { 175 int current = get(); 176 int next = current - 1; 177 if (compareAndSet(current, next)) 178 return next; 179 } 180 } 181 182 183 188 public final int addAndGet(int delta) { 189 for (;;) { 190 int current = get(); 191 int next = current + delta; 192 if (compareAndSet(current, next)) 193 return next; 194 } 195 } 196 197 201 public String toString() { 202 return Integer.toString(get()); 203 } 204 205 206 public int intValue() { 207 return get(); 208 } 209 210 public long longValue() { 211 return (long)get(); 212 } 213 214 public float floatValue() { 215 return (float)get(); 216 } 217 218 public double doubleValue() { 219 return (double)get(); 220 } 221 222 } 223 | Popular Tags |