- 當(dāng)AtomicInteger的值為最大值2147483647時,執(zhí)行incrementAndGet()會發(fā)生什么晾嘶?
- 當(dāng)AtomicInteger的值為最小值-2147483648時果覆,執(zhí)行decrementAndGet()會發(fā)生什么摇幻?
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());
測試結(jié)果如下:
2147483647
-2147483648
--------------------
-2147483648
2147483647
有時候并不能符合我們的業(yè)務(wù)場景,比如隊列消息從0開始增加顷锰,當(dāng)增加到最大值時我們不希望下一個值為負(fù)數(shù)柬赐。而是從0開始,周而復(fù)始官紫,對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;
}