Does RandomStringUtils create a deterministic or reproducible sequence?

Viewed 258

On a Java application server we use RandomStringUtils.randomAlphabetic() to sequentially create HTML-IDs for recurring similar paragraphs in an iterating manner.

Via these generated IDs, we allow for an inner-page anchor navigation (without a page load triggered upon click).

Now the question is, can I use these generated IDs also for URLs linking from external pages to this target? According to my observation, subsequent requests to the same page, create the same sequence of IDs. If the generated sequence of randomAlphabetic is indeed predictable (also over multiple page loads), we could not only use these links for inner-page navigation, but also for links referring from outside, since the first, second, third, ... generated ID would always be the same.

1 Answers

If the "random" ID is always the same for a given text string of a paragraph (that is, the ID is solely a function of a paragraph's text), then you should consider hash functions, rather than pseudorandom number generators such as randomAlphabetic. (I assume that for your use case of identifying parts of a page, the risk of generating duplicate IDs for different text strings is negligible. If you can't tolerate this risk, though, hash functions should not be used.) There are many kinds of hash functions for this purpose; even java.lang.String.hashCode() will work here since the Java documentation for this method specifies the exact algorithm it uses.

Moreover, randomAlphabetic is not "deterministic" in the sense you want for two reasons:

  • You can't set the seed of the underlying generator the method uses (RandomStringUtils stores a static PRNG variable initialized with an undefined seed, namely new Random()).
  • The documentation for RandomStringUtils.randomAlphabetic (among other RandomStringUtils methods) doesn't specify the exact algorithm it uses to generate random strings.
Related