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.