consider the (optional) use of ThreadLocal(Random)
See original GitHub issueThe uuid-creator (and ulid-creator) uses internally java.util.Random . This could lead to contention (and latency) if a very high number of threads generate uuid/ulid at the same time. Because java uses a single shared SecureRandom (and Random) instance to generate the random bits.
The java.util.concurrent.ThreadLocalRandom extends Random to eliminate such issues. Maybe you can include this idea within the Generator-Patterns of uuid and ulid (e.g., .withTreadLocal()).
UuidCreator
.getUlidBasedCreator()
.withTreadLocal()
.withFastRandomGenerator()
Another alternative is to put the SecureRandom (Random) or any other Random derived classes into a ThreadLocal (don’t forget to remove() the thread local to avoid memory leaks).
Another alternative is to use a buffer of precreated uuid/ulids:
UuidCreator
.getUlidBasedCreator()
// uses a buffer if available by a previous call or creates one with 1000
// the next caller gets the value from the buffer
.fromBuffer(1000)
.withFastRandomGenerator()
But I think the TreadLocal-approach would be good enough.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)

Top Related StackOverflow Question
With second option you mean
ThreadLocal.withInitialor the buffer-solution?Yes, good point. I find out that
UUID.randomUUID()on Java 8+ removed thesynchronizedand uses/dev/urandom(-> non-blocking) instead of/dev/random(-> blocking). Read more: https://tersesystems.com/blog/2015/12/17/the-right-way-to-use-securerandom/According to the measurement of https://github.com/apache/openwhisk/issues/2747, ThreadLocal[SecureRandom] is also prefered instead of ThreadLocalRandom. But I don’t know if or how they solve the potential memory leaks when using ThreadLocal[SecureRandom] (https://github.com/apache/openwhisk/pull/2785/commits/f66c78d117cbb941ca8671732dd59546df804eae). Btw, the objects stored in the ThreadLocal are from the system ClassLoader, not the webapp’s ClassLoader…so the potential memory leak can occur on the system class loader…
Maybe the pooling-solution (which acts like a buffer) is a better solution? But then the pooling will always preserves numbers in the memory…I think ThreadLocal[SecureRandom] is a clean solution but I am unsure how to treat potential memory leaks…
Thanks again!