Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active February 11, 2021 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petitviolet/89886339e028779172a293a01e18d8f0 to your computer and use it in GitHub Desktop.
Save petitviolet/89886339e028779172a293a01e18d8f0 to your computer and use it in GitHub Desktop.
[Scala]ThreadLocalRandom is fast.

ThreadLocalRandom is faster than Random

val n = 100
Random.nextInt(n)
ThreadLocalRandom.current().nextInt(n)

why ThreadLocalRandom is faster

scala.util.Random#nextInt uses AtomicInteger at java.util.Random#next for generating thread-safe random.
On the one hand, ThreadLocalRandom overrides next method to make it non thread-safe and faster.

Random.nextInt(n)

    protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) & mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed >>> (48 - bits));
    }

ThreadLocalRandom.current().nextInt(n)

  protected int next(int bits) {
    this.rnd = this.rnd * 25214903917L + 11L & 281474976710655L;
    return (int)(this.rnd >>> 48 - bits);
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment