How to Generate Unique ID in Java (Integer)?

后端 未结 9 1504
生来不讨喜
生来不讨喜 2020-12-06 04:11

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

9条回答
  •  萌比男神i
    2020-12-06 05:09

    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.

提交回复
热议问题