【问题标题】:Generate auto increment id in java在java中生成自动增量ID
【发布时间】:2016-02-02 06:21:39
【问题描述】:

在如何生成自动增量 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 中不可用。

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

【问题讨论】:

  • its never start to 0 again, its always start with the last increment id - 这不是自动增量的主题吗?还是您在问如何在0 重新启动?
  • 我在问如何再次将其重置为0。
  • 你怎么知道这次应该是0而不是自增1?
  • 你想什么时候重置回0?

标签: java


【解决方案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;  
    }
}

【讨论】:

    【解决方案2】:
    private static AtomicInteger count = new AtomicInteger(0);    
    count.set(0);    
    uniqueID = count.incrementAndGet();
    

    【讨论】:

    • 我不知道你是否看到了 OP 的编辑:“除了AtomicInteger,还有其他方法吗?” 另外,没有解释的只有代码的答案通常是不受欢迎的.
    猜你喜欢
    • 2016-09-27
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多