0

I have already asked this before how to generate auto increment ID Generate auto increment number by using Java.

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. For this static its never start to 0 again, its always start with the last increment id. That is the issue.

Is there any alternative way except AtomicInteger?

Another issue is that I am working on GWT so AtomicInteger is not available in GWT.

So I have to find another way to do that.

Community
  • 1
  • 1
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94

2 Answers2

1

AtomicInteger is a "signed" integer. It will increase till Integer.MAX_VALUE; then, due to integer overflow, you expect to get Integer.MIN_VALUE.

Unfortunately, most of the thread safe methods in AtomicInteger are final, including incrementAndGet(), so you cannot override them.

But you could create a custom class that wraps an AtomicInteger and you just create synchronized methods according to your needs. 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;  
    }
}
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24
0
private static AtomicInteger count = new AtomicInteger(0);    
count.set(0);    
uniqueID = count.incrementAndGet();
Rey
  • 7
  • 2
  • I don't know if you saw OP's edit: *"Is there any alternative way except `AtomicInteger`?"* Also, code only answers with no explanations are usually frowned upon. – Jonny Henly Feb 02 '16 at 07:00