How to get 32 bits unique number in Java?

11,007

How "unique" are you wanting? In short, what is the collision domain? If you are dealing with thousands of keys then Random.nextInt() does exactly what you want relative to what you tried with version 4 UUIDs (UUID v4 generates 128 random bits).

If you need something with a less chance of collision then you need to have a globally incremented integer but there is much care to be taken here such as keeping state between JVM startups. For that you should look into AtomicIntegers.

Share:
11,007
X.M.
Author by

X.M.

Updated on June 05, 2022

Comments

  • X.M.
    X.M. almost 2 years

    I need to generate an unique number of 32 bits in Java. I need to return the number as Java int, which is required by the interface. Can you please share some ideas on this?

    The number will be used as MySQL PK and several threads could be generating their own unique id at same time. (Sorry it is decided not to use MySQL incremental id)

    I tried UUID class but it seems the data it generates has more bits than I can use.

    I found this but not sure if it works:

        // seems no way to get int
        UUID id = UUID.randomUUID();
        System.out.println(id);
    
        // not working either?
        java.rmi.server.UID uid = new java.rmi.server.UID();
        System.out.println(uid.toString());
    
        // the one i am using
        SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
        prng.setSeed(System.currentTimeMillis());
        int ret = prng.nextInt();
        System.out.println(ret);