[英]Generate auto increment id in java
I have already asked this before how to generate auto increment ID Generate auto increment number by using Java . 在使用Java生成自动增量ID之前,我已经问过这个问题。
I have used below code: 我用下面的代码:
private static final AtomicInteger count = new AtomicInteger(0);
uniqueID = count.incrementAndGet();
The previous code working fine but the problem is count
static variable. 先前的代码工作正常,但问题是
count
静态变量。 For this static its never start to 0
again, its always start with the last increment id. 对于此静态变量,它永远不会再从
0
开始,它总是从最后一个增量ID开始。 That is the issue. 这就是问题。
Is there any alternative way except AtomicInteger
? 除了
AtomicInteger
还有其他方法吗?
Another issue is that I am working on GWT so AtomicInteger
is not available in GWT. 另一个问题是我正在研究GWT,因此
AtomicInteger
在GWT中不可用。
So I have to find another way to do that. 因此,我必须找到另一种方法。
AtomicInteger
is a "signed" integer. AtomicInteger
是一个“有符号”整数。 It will increase till Integer.MAX_VALUE
; 它将增加到
Integer.MAX_VALUE
; then, due to integer overflow, you expect to get Integer.MIN_VALUE
. 然后,由于整数溢出,您期望获得
Integer.MIN_VALUE
。
Unfortunately, most of the thread safe methods in AtomicInteger
are final, including incrementAndGet()
, so you cannot override them. 不幸的是,
AtomicInteger
中的大多数线程安全方法都是最终的,包括incrementAndGet()
,因此您无法覆盖它们。
But you could create a custom class that wraps an AtomicInteger and you just create synchronized
methods according to your needs. 但是您可以创建一个包装AtomicInteger的自定义类,并根据需要创建
synchronized
方法。 For instance: 例如:
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;
}
}
private static AtomicInteger count = new AtomicInteger(0);
count.set(0);
uniqueID = count.incrementAndGet();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.