简体   繁体   中英

Make class generate short sequential unique ID

I have a class (below). I have the field id for the class but I dont know how to make this create a unique id increasing sequentially.

I found that UUID.randomUUID(); would generate a unique ID but in a very unfriendly way and with no way to limit size.

How could I implement something to increase the id field as objects are created from the below class?

class Customer {

public int id;
public String name;
public String email;
public String number;
public String issue;
public String expiry;

Customer(String eName, String eEmail, String eNumber, String eIssue, String eExpiry)
{
    id = 0935091285;
    name = eName;
    email = eEmail;
    number = eNumber;
    issue = eIssue;
    expiry = eExpiry;
}
}

You don't specify whether you have multiple processes simultaneously generating ids. If you don't, the following is simple and will work well:

public class Customer {
  private static AtomicInteger nextId = new AtomicInteger(0);
  private static String getNextId() {
    return Integer.toString(nextId.incrementAndGet());
  }
  public Customer(...) {
    id = getNextId();
    ...
  }
}

Format the numeric id with leading zeroes if you'd like lexicographic ordering of ids to reflect object creation order.

I'm not sure I understand why the UUID generator doesn't satisfy your needs. The size is fixed (36 characters). I can understand that the non sequential part could be a problem though.

If you need to generate unique identifiers sequentially (and given that you've tried UUID, I suppose that you've already tried a simple incremental system) and possibly on a large scale I would recommend you to take a look snowflake , the service used by twitter to generate sequential but non incremental ids.

Basically it's a simple server you can run and that will generate unique identifiers for you when you need it:

  • Thrift Server written in Scala
  • id is composed of:

    • time - 41 bits (millisecond precision w/ a custom epoch gives us 69 years)
    • configured machine id - 10 bits - gives us up to 1024 machines
    • sequence number - 12 bits - rolls over every 4096 per machine (with protection to avoid rollover in the same ms)

Resources:

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