Generate Unique number With AtomicLong


import java.util.concurrent.atomic.AtomicLong;

public class UniqueNumGenerator {

    //initial value is 0
    private static AtomicLong uniqueCounter = new AtomicLong(0);

    public static long nextId() {
        return uniqueCounter.incrementAndGet();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(UniqueNumGenerator.nextId());
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s