Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique keys using RandomStringUtils of apache commons

Please find the below code which I've used to generate random strings using RandomStringUtils of apache commons.

String key = RandomStringUtils.random(5, String.valueOf(System.currentTimeMillis()));

I am limiting the key to 5 characters. My purpose is generating unique keys for each records when I'm inserting a new record to DB. Will the above code be suitable for corresponding task and could I be assured that I will get a unique key from the above code each time inserting a new record.

like image 981
нαƒєєz Avatar asked Dec 12 '22 09:12

нαƒєєz


2 Answers

A random sequence of strings will always have a possibility of repeating, otherwise it's not really random. RandomStringUtils is not really random, but it's trying to be as close to random as it can be, which seems contrary to your goal. If you must use randomly generated keys, then you should at least use java.util.UUID.randomUUID because that is made to be used that way.

You may find this link interesting: Generating unique IDs

like image 86
Geo Avatar answered Dec 29 '22 10:12

Geo


No, random doesn't mean unique. You can try using UUIDs to generate unique keys.

like image 26
Dumindu Pallewela Avatar answered Dec 29 '22 10:12

Dumindu Pallewela