How do I generate unique Long Id in Java ?

There are many ways to generate unique Long Id in java. You can use LongGenerator by apache commons id to generate unique Long id.

Unique Long id using LongGenerator

LongGenerator is an Identifier Generator that generates an incrementing number as a Long object. The below example shows you how to generate unique long id using apaches commons id LongGenerator nextLongIdentifier() method

package com.sneppets.java;

import org.apache.commons.id.serial.LongGenerator;

public class LongGeneratorTest {
	
	public static void main (String[] args) {
		
		//args -> wrap(false) and initial value (100)		
		LongGenerator lg = new LongGenerator(false, 100L);
		
		for(int i=0; i<10; i++) {
			Long uniqueLongId = lg.nextLongIdentifier();
			System.out.println("Long Id : {}"+ uniqueLongId.longValue());
		}
	}

}

Below is the LongGenerator class that is used in the above example

public class LongGenerator extends AbstractLongIdentifierGenerator implements Serializable {

    /**
     * <code>serialVersionUID</code> is the serializable UID for the binary version of the class.
     */
    private static final long serialVersionUID = 20060122L;

    /** Should the counter wrap. */
    private boolean wrapping;
    /** The counter. */
    private long count = 0;
    
    /**
     * Constructor.
     *
     * @param wrap should the factory wrap when it reaches the maximum
     *  long value (or throw an exception)
     * @param initialValue  the initial long value to start at
     */
    public  LongGenerator(boolean wrap, long initialValue) {
        super();
        this.wrapping = wrap;
        this.count = initialValue;
    }

    /**
     * Getter for property wrap.
     *
     * @return <code>true</code> if this generator is set up to wrap.
     *
     */
    public  boolean isWrap() {
        return wrapping;
    }

    /**
     * Sets the wrap property.
     *
     * @param wrap value for the wrap property
     *
     */
    public  void setWrap(boolean wrap) {
        this.wrapping = wrap;
    }
    
    public  Long nextLongIdentifier() {
        long value = 0;
        if (wrapping) {
            synchronized (this) {
                value = count++;
            }
        } else {
            synchronized (this) {
                if (count == Long.MAX_VALUE) {
                    throw new IllegalStateException
                    ("The maximum number of identifiers has been reached");
                }
                value = count++;
            }
        }
        return new Long(value);
    }
}

Using AtomicLong

You can also implement simply by atomically incrementing a counter if that suits your needs. AtomicLong can be used in applications such as atomically incremented sequence numbers. Create an util called LongCounter as shown below.

package com.sneppets.util;

import java.util.concurrent.atomic.AtomicLong;

public class LongCounter {
	
	private LongCounter() {
		
	}	
	private static final AtomicLong acounter = new AtomicLong(0);
	
	public static long getNextLongNumber() {
		return acounter.incrementAndGet();
	}

}

Then call LongCounter.getNextLongNumber() to get the incremented long number value.

Further Learning:

References

Leave a Reply

avatar
  Subscribe  
Notify of