Reputation: 73
I need to make a servlet service that does following things
when user request the service, servlet generates a unique 5 letter string that has never been generated. (combination of 0~9 and a~Z)
if user accepts it, save user's info using the unique string(that #1 generated) as a primary key
First thing popped in my head was using static class variable that increments by 1 as requests hit servlet, but searching here and google says this is really really bad idea, as if multiple users hit the service at the same time, it will break...
and now I am clueless what to look into.
What would be the best and the safetest approach to generate a unique string incrementally?
Upvotes: 0
Views: 96
Reputation: 17455
According to this site, your highest number (ZZZZZ) is 426088025. In the database world you'd want to used a sequence but, because of your 5 character restriction, you need to make sure that it doesn't go over this number (hopefully you're storing less than 426M records).
To create a sequence you'll do something like:
create sequence your_sequence maxvalue 426088025 no cycle
That is the PostgreSQL syntax - your database may vary.
Then, in your code you can do a
select nextval('your_sequence')
to get your value and then Base64 encode this value. In PostgreSQL the "no cycle" means that if you get to the max it will throw an error.
In Java 8, Base64 is included:
import java.util.Base64;
...
String userNumber = Base64.getEncoder().encodeToString(Integer.toString(integerFromSequenceSelect));
Otherwise, if you're stuck with an old version of Java, use Apache Commons Codec and run:
import org.apache.commons.codec.binary.Base64;
...
String userNumber = Base64.encodeBase64String(Integer.toString(integerFromSequenceSelect));
Upvotes: 0
Reputation: 75
Add a field sequence no in table and when ever a new request comes get the highest sequence number from database and then add one ie plus 1 and save it
Upvotes: 1