- 当AtomicInteger的值为最大值2147483647时,执行incrementAndGet()会发生什么?
- 当AtomicInteger的值为最小值-2147483648时,执行decrementAndGet()会发生什么?
AtomicInteger max = new AtomicInteger(Integer.MAX_VALUE);
System.out.println(max);
System.out.println(max.incrementAndGet());
System.out.println("--------------------");
AtomicInteger min = new AtomicInteger(Integer.MIN_VALUE);
System.out.println(min);
System.out.println(min.decrementAndGet());
测试结果如下:
2147483647
-2147483648
--------------------
-2147483648
2147483647
有时候并不能符合我们的业务场景,比如队列消息从0开始增加,当增加到最大值时我们不希望下一个值为负数。而是从0开始,周而复始,对incrementAndGet和decrementAndGet分别做如下改造:
private final AtomicInteger i;
public final int incrementAndGet() {
int current;
int next;
do {
current = this.i.get();
next = current >= 2147483647?0:current + 1;
} while(!this.i.compareAndSet(current, next));
return next;
}
public final int decrementAndGet() {
int current;
int next;
do {
current = this.i.get();
next = current <= 0?2147483647:current - 1;
} while(!this.i.compareAndSet(current, next));
return next;
}