繁体   English   中英

在Java中生成自动增量ID

[英]Generate auto increment id in java

使用Java生成自动增量ID之前,我已经问过这个问题。

我用下面的代码:

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的自定义类,并根据需要创建synchronized方法。 例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM