简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM