Since you have chosen to use Java code to generate a unique identifier, I want to say that you should generate a unique identifier that combines a "unique" part and a "random" part. Note that your current answer doesn't exactly meet the "unpredictable" requirement, since it uses Math.random()
, which is not necessarily an "unpredictable" RNG.
- The "unique" part can be a monotonically increasing counter, or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating). I don't recommend timestamps alone since the risk exists of generating the same timestamp in rapid succession.
- The "random" part is simply a random number generated with a cryptographic random number generator (which for Java is
java.security.SecureRandom
; use the "DRBG" implementation rather than "SHA1PRNG" if available). In general, the longer the random part is, the less predictable it will be.
Your current code is on the right track, but you should concatenate the two parts of the random ID (like they were strings) rather than adding an arbitrary offset to the current time (e.g., what if cal.getTimeInMillis()
returns a number greater than Min
?).