Search code examples
javajakarta-eeapache-commonshashcode

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.


Solution

  • 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