简体   繁体   中英

How to Generate Unique ID in Java (Integer)?

java - 如何在java中生成不猜测下一个数字的整数的唯一ID?

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.

int uniqueId = 0;

int getUniqueId()
{
    return uniqueId++;
}

Add synchronized if you want it to be thread safe.

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.

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.

 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.

只需生成ID并检查它是否已存在于生成的ID列表中。

Do you need it to be;

  • unique between two JVMs running at the same time.
  • unique even if the JVM is restarted.
  • thread-safe.
  • support null? if not, use int or long.

if only int is required then AtomicInteger can make it possible.

if String is needed then the below code should work by mixing timeStamp and AtomicLong.

AtomicLong idCounter =  new AtomicLong(100);
long timestamp = System.currentTimeMillis();
long nextLong = idCounter.incrementAndGet();
String randomId = String.valueOf(timestamp)+String.valueOf(nextLong); 

随时独特:

int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM