我之前已经问过这个如何生成自增ID Generate auto increment number by using Java .
我使用了以下代码:
private static final AtomicInteger count = new AtomicInteger(0);
uniqueID = count.incrementAndGet();
之前的代码工作正常,但问题是 count
静态变量。对于这个静态,它永远不会再从 0
开始,它总是从最后一个增量 id 开始。这就是问题所在。
除了AtomicInteger
之外还有其他方法吗?
另一个问题是我正在使用 GWT,因此 AtomicInteger
在 GWT 中不可用。
所以我必须找到另一种方法来做到这一点。
最佳答案
AtomicInteger
是一个“有符号”整数。它将增加直到Integer.MAX_VALUE
;然后,由于整数溢出,您期望得到 Integer.MIN_VALUE
。
不幸的是,AtomicInteger
中的大多数线程安全方法都是最终的,包括 incrementAndGet()
,因此您无法覆盖它们。
但是您可以创建一个包装 AtomicInteger 的自定义类,并且只需根据您的需要创建同步
方法即可。例如:
public class PositiveAtomicInteger {
private AtomicInteger value;
//plz add additional checks if you always want to start from value>=0
public PositiveAtomicInteger(int value) {
this.value = new AtomicInteger(value);
}
public synchronized int incrementAndGet() {
int result = value.incrementAndGet();
//in case of integer overflow
if (result < 0) {
value.set(0);
return 0;
}
return result;
}
}
关于java - java生成自增id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35146440/