java - ThreadLocalRandom or AtomicInteger -


i have need generate non-overlapping numbers (random or incremental doesnt matter each generated number unique) in multiple threads. think have 2 choices

  1. use atomicinteger , share across threads
  2. use threadlocalrandom different start , end ranges each thread

i need fast , numbers should unique across threads. 1 better?

option 1 slower because atomicinteger provides thread safety through use of volatile int - meaning modifications or reads must always fetch from/write ram, slower reading/writing in processor's cache memory.

option 2 might faster (depending on how time takes calculate next number in sequence vs. memory fetch), run risk (albeit small) of generating duplicate numbers randomly.

might suggest third option? use thread local int or long pre-defined range. won't have worry cache coherency 1 thread have access each primitive counter store. still run risk of wrap-around, know when happens, unlike risk of running duplicates on random number sequence.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -