Aravind Yarram
Aravind Yarram

Reputation: 80166

ThreadLocalRandom or AtomicInteger

I have a need to generate non-overlapping numbers (random or incremental doesnt matter as each generated number is unique) in multiple threads. I think I have two choices

  1. Use AtomicInteger and share it across all threads
  2. Use ThreadLocalRandom with different start and end ranges for each thread

I need this to be very fast and also the numbers should be unique across all the threads. Which one is better?

Upvotes: 1

Views: 550

Answers (1)

CodeBlind
CodeBlind

Reputation: 4569

Option 1 will be slower because AtomicInteger provides thread safety through the use of a volatile int - meaning modifications or reads must always fetch from/write to RAM, which will always be slower than reading/writing in the processor's cache memory.

Option 2 might be faster (depending on how much time it takes to calculate the next number in the sequence vs. a memory fetch), but you run the risk (albeit small) of generating duplicate numbers randomly.

Might I suggest a third option? Use a thread local int or long with a pre-defined range. You won't have to worry about cache coherency as only one thread will have access to each primitive counter you store. You still run the risk of wrap-around, but you will know exactly when it happens, unlike the risk of running into duplicates on a random number sequence.

Upvotes: 3

Related Questions