0

There is a requirement in which I need to generate alphanumeric strings of length 8. There are lot questions on Stack Overflow, but I was not able to find one specific to my requirement.

I need to generate barcodes on which I need to show this string. I can generate as suggested in this Stack Overlow question, but what if

  1. My application is running multiple instances? There may be a case of having duplicate generated string.

  2. What happens when application restarts? As it is not maintaining states or last generated values.

I could use a database like MySQL with unique key constraints to mitigate these issues, but still I think (correct me please) it is not the standard way to implement this solution, because in this too I need to handle the exception of unique key constraints and try to generate again until I get a unique value.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
SBhogal
  • 119
  • 2
  • 15
  • Does this answer your question? [Compact alternatives to UUID as a correlationId](https://stackoverflow.com/questions/63409443/compact-alternatives-to-uuid-as-a-correlationid) – Peter O. Nov 11 '21 at 07:17
  • Note in particular: "If your application is distributed across multiple computers, you might choose to assign each computer a unique value to include in the ID." – Peter O. Nov 11 '21 at 07:18
  • A length 8 alphanumeric string is an 8 digit number in base 62 (26 + 26 + 10). Assign different ranges to each computer, generate numbers within the assigned range and convert to base 62. – rossum Nov 11 '21 at 08:58
  • @rossum but what if an application instance is restarted with assigned range X to Y let's say...then will it not start generating string's which are already generated. – SBhogal Nov 11 '21 at 11:54
  • There are various ways to ensure that a 'random' number is not a duplicate. See [here](https://stackoverflow.com/questions/68626210/kotlin-random-numbers-without-repeating/68626417#68626417) for some ideas. – rossum Nov 11 '21 at 12:24

0 Answers0