# Thread Local Randoms in Java

DevFeed: [Thread Local Randoms in Java](<https://devfeed.tech/articles/thread-local-randoms-in-java-24841.md>)

Original publisher: [Read original article](<https://alidg.me/blog/2020/4/24/thread-local-random>)

Author: Alimate

Published: 2020-04-24T00:00:00Z

Content type: article

Language: en

Sources: [Ali Dehghan - Kemikit](<https://devfeed.tech/sources/ali-dehghan-kemikit.md>)

Topics: [Benchmark](<https://devfeed.tech/topics/benchmark.md>), [Java](<https://devfeed.tech/topics/java.md>), [thread safe data sharing](<https://devfeed.tech/topics/thread-safe-data-sharing.md>), [Algorithms](<https://devfeed.tech/topics/algorithms.md>), [locking](<https://devfeed.tech/topics/locking.md>)

Tags: [algorithm](<https://devfeed.tech/tags/algorithm.md>), [atomics](<https://devfeed.tech/tags/atomics.md>), [benchmark](<https://devfeed.tech/tags/benchmark.md>), [cas](<https://devfeed.tech/tags/cas.md>), [concurrent](<https://devfeed.tech/tags/concurrent.md>), [concurrently](<https://devfeed.tech/tags/concurrently.md>), [generation](<https://devfeed.tech/tags/generation.md>), [generator](<https://devfeed.tech/tags/generator.md>), [global](<https://devfeed.tech/tags/global.md>), [java](<https://devfeed.tech/tags/java.md>), [linear](<https://devfeed.tech/tags/linear.md>), [lock-free](<https://devfeed.tech/tags/lock-free.md>), [memory](<https://devfeed.tech/tags/memory.md>), [ordering](<https://devfeed.tech/tags/ordering.md>), [performance](<https://devfeed.tech/tags/performance.md>), [random](<https://devfeed.tech/tags/random.md>), [retry](<https://devfeed.tech/tags/retry.md>), [shared-mutable-state](<https://devfeed.tech/tags/shared-mutable-state.md>), [synchronization](<https://devfeed.tech/tags/synchronization.md>), [thread](<https://devfeed.tech/tags/thread.md>)

## AI overview

The excerpt attributes poor concurrent throughput in shared random generation to contention: Java's implementation updates a shared seed with atomic compare-and-set retries, which can fail repeatedly under load. A thread-local approach avoids shared mutable state and the associated atomicity and memory-ordering costs; in the reported benchmark, it achieved almost twice the throughput of the author's simple implementation. The built-in random generator still outperformed both approaches. The excerpt begins to describe a further optimization--keeping only each thread's latest value instead of a full per-thread generator copy--but cuts off before giving its implementation or results.

## Source excerpt

Benchmarking regular randoms against thread-local ones!