src/share/classes/java/util/concurrent/atomic/AtomicInteger.java
Print this page
@@ -113,16 +113,12 @@
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
- for (;;) {
- int current = get();
- if (compareAndSet(current, newValue))
- return current;
+ return unsafe.getAndSetInt(this, valueOffset, newValue);
}
- }
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
@@ -143,11 +139,11 @@
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
- * @return true if successful.
+ * @return true if successful
*/
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
@@ -155,93 +151,63 @@
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final int getAndIncrement() {
- for (;;) {
- int current = get();
- int next = current + 1;
- if (compareAndSet(current, next))
- return current;
+ return getAndAdd(1);
}
- }
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final int getAndDecrement() {
- for (;;) {
- int current = get();
- int next = current - 1;
- if (compareAndSet(current, next))
- return current;
+ return getAndAdd(-1);
}
- }
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
- for (;;) {
- int current = get();
- int next = current + delta;
- if (compareAndSet(current, next))
- return current;
+ return unsafe.getAndAddInt(this, valueOffset, delta);
}
- }
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
- for (;;) {
- int current = get();
- int next = current + 1;
- if (compareAndSet(current, next))
- return next;
+ return getAndAdd(1) + 1;
}
- }
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final int decrementAndGet() {
- for (;;) {
- int current = get();
- int next = current - 1;
- if (compareAndSet(current, next))
- return next;
+ return getAndAdd(-1) - 1;
}
- }
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final int addAndGet(int delta) {
- for (;;) {
- int current = get();
- int next = current + delta;
- if (compareAndSet(current, next))
- return next;
+ return getAndAdd(delta) + delta;
}
- }
/**
* Returns the String representation of the current value.
- * @return the String representation of the current value.
+ * @return the String representation of the current value
*/
public String toString() {
return Integer.toString(get());
}