public class CircularAtomicInteger {
private final int minValue;
private final int maxValue;
private final AtomicInteger atomicInteger;
public CircularAtomicInteger(int initialValue, int minValue, int maxValue) {
this.minValue = minValue;
this.maxValue = maxValue;
this.atomicInteger = new AtomicInteger(initialValue);
}
/**
* 自增
* @return
*/
public int incrementAndGet() {
int currentValue;
int updatedValue;
do {
currentValue = atomicInteger.get();
updatedValue = currentValue >= maxValue ? minValue : currentValue + 1;
} while (!atomicInteger.compareAndSet(currentValue, updatedValue));
return updatedValue;
}
/**
* 自减
* @return
*/
public int decrementAndGet() {
int currentValue;
int updatedValue;
do {
currentValue = atomicInteger.get();
updatedValue = currentValue <= minValue ? maxValue : currentValue - 1;
} while (!atomicInteger.compareAndSet(currentValue, updatedValue));
return updatedValue;
}
}