-1

I have a requirement where we need to generate unqiue block ID which will be 11 characters.

We have below logic to generate it,

public String generateBlockId(){
        boolean alreadyExists = true;
        String newBlockId = "";
        
        while(alreadyExists) {
        
            newBlockId = generateYYDDDSSSSSString();
            
            Allocation allocation = repo.findTopByBlockId(newBlockId);
            if(allocation == null) {
                blockIdAlreadyExists = false;
            }
        }
        
        return newBlockId;
    }
    
    
public String generateYYDDDSSSSSString() {
        String dateString;
        LocalDateTime now = LocalDateTime.now();
        Integer year = now.getYear() % 100;
        Integer day = now.getDayOfYear();
        Integer second = now.toLocalTime().toSecondOfDay();
        String YY = StringUtils.leftPad(year.toString(), 2, "0");
        String DDD = StringUtils.leftPad(day.toString(), 3, "0");
        String SSSSSS = StringUtils.leftPad(second.toString(), 6, "0");
        dateString = YY + DDD + SSSSSS;
        return dateString;
    }

We have utmost 100 concurrent users at time and it is having performance impact and causing unique constraint exception when generated id is stored to the DB.

Is there any better solution to this issue.

Note : The business requirement is to have 11 digits only.

vasantharajan
  • 265
  • 5
  • 18
  • 1
    Well, a timestamp is rarely unique so there is a chance 2 users generate the id in the same second. Why don't you use a simple sequence generator, either in code or in your DB to handle this? – Thomas Jan 04 '22 at 07:26
  • @Thomas . This is only 11 characters, so there is a chance in future it may run out of sequence! – vasantharajan Jan 04 '22 at 07:35
  • Sure, but no matter how you're generating those numbers you'll eventually run out of sequence. An 11-digit number allows for up to 1 trillion unique ids so if you're afraid your application will use more then using a second-precision timestamp will be even riskier. – Thomas Jan 04 '22 at 07:39

2 Answers2

0

First things first - maybe you should get back to business and verify why they need 11 digits constraint ;)

Anyway if particular user can make only one request at a time (i.e. no concurrent request from single user) I would include user id (or some part of it) in generated id. In such case generated ids should not overlap.

Mariusz W.
  • 116
  • 3
0

I think I probably did not get the question but I will do my best.

perhaps a better way would be to use UUIDs? is using timestamp a requirement?

I added an example below

    public static String generateId() {
    //Create new uuid
    UUID uuid = UUID.randomUUID();
    //Convert the uuid to string and strip it from "-"
    String id = uuid.toString().replace("-", "");
    //Trim the UUID and retrieve the chars until the 11th char.
    id = id.substring(0, 11);
    //Return the id back
    return id;
}
iSoda
  • 23
  • 5