How to Generate Unique ID in Java (Integer)?

111,327

Solution 1

How unique does it need to be?

If it's only unique within a process, then you can use an AtomicInteger and call incrementAndGet() each time you need a new value.

Solution 2

int uniqueId = 0;

int getUniqueId()
{
    return uniqueId++;
}

Add synchronized if you want it to be thread safe.

Solution 3

 import java.util.UUID;

 public class IdGenerator {
    public static int generateUniqueId() {      
        UUID idOne = UUID.randomUUID();
        String str=""+idOne;        
        int uid=str.hashCode();
        String filterStr=""+uid;
        str=filterStr.replaceAll("-", "");
        return Integer.parseInt(str);
    }

    // XXX: replace with java.util.UUID

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

}

Hope this helps you.

Solution 4

It's easy if you are somewhat constrained.

If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.

If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).

The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.

In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:

return (myID << 16) & uniqueID++

It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...

If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.

Solution 5

If you really meant integer rather than int:

Integer id = new Integer(42); // will not == any other Integer

If you want something visible outside a JVM to other processes or to the user, persistent, or a host of other considerations, then there are other approaches, but without context you are probably better off using using the built-in uniqueness of object identity within your system.

Share:
111,327

Related videos on Youtube

Sajad Bahmani
Author by

Sajad Bahmani

Favorite Languages : Java , Scala , Bash , C/C++ , Python Favorite IDE : IntelliJ IDEA , Netbeans Favorite Editor : VSCode , Vim

Updated on July 09, 2022

Comments

  • Sajad Bahmani
    Sajad Bahmani almost 2 years

    How to generate unique ID that is integer in java that not guess next number?

    • svachon
      svachon about 14 years
      Perhaps you should be a little more precise about the context of your needs.
  • BalusC
    BalusC about 14 years
    That doesn't return an integer. Format is hexstring, like 20e8f3d6-3f8d-475b-8c19-9619a78bbdc8.
  • Adamski
    Adamski about 14 years
    @BalusC: This is merely the String output you're talking about. Internally a UUID is a 128-bit value and hence could be interpreted as an integer (albeit BigInteger).
  • BalusC
    BalusC about 14 years
    Still, it doesn't fit in an integer.
  • sixtyfootersdude
    sixtyfootersdude about 14 years
    Might want to add an exception for when it the integers get too high and roll over. Also might want to start uniqueId at Integer.MinInt() (Method is called something like that).
  • reccles
    reccles about 14 years
    Even better to prime AtomicInteger with Integer.MIN_VALUE. This helps in debugging and gives you more numbers to play with.
  • talonx
    talonx about 14 years
    This will work only when the process runs forever without stopping. For restarted apps, it will start from 0 each time.
  • fmunshi
    fmunshi over 11 years
    -1. While a UUID will certainly provide a unique value, there's no guarantee that this uniqueness guarantee persists when you take its hashcode. You may as will pick a random number between Integer.MIN_VALUE and Integer.MAX_VALUE and hope for the best.
  • Christopher Barber
    Christopher Barber about 11 years
    Not so. UUID.randomUUID() uses a cryptographically strong random number generator, so that should be better than using a weaker pseudorandom number generator.
  • user1071840
    user1071840 almost 10 years
    Bill K. gave a solution for the first case, i.e. what can be done if want the id to be unique between 2 JVMs. What's the right approach to make sure that the id is unique even after JVM restarts?
  • user1071840
    user1071840 almost 10 years
    Oh, requesting a uniqueId from one of a centralized databases will work after restarts too.
  • Matthias
    Matthias over 9 years
    Referring to this answer, System.currentTimeMillis() does not return unique values.
  • Dmitry Zagorulkin
    Dmitry Zagorulkin over 8 years
    also you need to think about overflow. smth like if (curInt == Integer.MAX_INT) reset atomicInteger
  • Jan Bodnar
    Jan Bodnar over 7 years
    Well, one might think about using a Long instead of Integer in the first place.