1

I have a task to generate a unique string, the first thought which came to my mind was to use Java's UUID generator with additional improvements. And so my way of generating a random string looks something like this

public static String generateRandomString() {
    return "TEST" + 
            DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSSSS")
                    .format(LocalDateTime.now()) + UUID.randomUUID()
            .toString().replace("-", "");
}

would this method generating a random string would be sufficient to achieve uniqueness having in mind that I need to generate 10 000 000 of them on a daily basis for the next 20 years. Also, this piece of code will be spinning on different JVM and potentially on different servers.

miroana
  • 494
  • 3
  • 22

2 Answers2

3

UUID.randomUUID() generates a type-4 UUID.

According to Wikipedia:

Thus, the probability to find a duplicate within 103 trillion version-4 UUIDs is one in a billion.

More info.

Adrian Russo
  • 546
  • 4
  • 16
2

Just do the maths:

10000000*365*20 =                             73000000000
2^128           = 340282366920938463463374607431768211456

I'd say you can use it after comparing these numbers.

EDIT: I just saw a few other answers, definitely check if UUID.randomUUID() uses the full 128 bits or only some.

  • How this number 2^128 would be impacted knowing that multiple JVM could generate a random string using this very same method? – miroana Jan 11 '21 at 21:11
  • A version 4 UUID returned by `UUID.randomUUID()` has 122 random bits. https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) – dnault Jan 11 '21 at 21:18
  • 2
    @miroana Nothing to worry about, see https://stackoverflow.com/questions/1155008/how-unique-is-uuid – Progman Jan 11 '21 at 21:18