在java

时间:2016-02-02 06:21:40

标签: java

我之前已经问过如何生成自动增量ID Generate auto increment number by using Java

我使用了以下代码:

private static final AtomicInteger count = new AtomicInteger(0);   
uniqueID = count.incrementAndGet(); 

以前的代码工作正常,但问题是count静态变量。对于这个静态,它永远不会再次开始0,它始终以最后一个增量id开始。这就是问题所在。

除了AtomicInteger之外还有其他方法吗?

另一个问题是我正在研究GWT,因此GWT中没有AtomicInteger

所以我必须找到另一种方法来做到这一点。

2 个答案:

答案 0 :(得分:1)

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;  
    }
}

答案 1 :(得分:0)

private static AtomicInteger count = new AtomicInteger(0);    
count.set(0);    
uniqueID = count.incrementAndGet();
相关问题