Saturday, May 30, 2015

`java.util.Random` is thread-safe?

`java.util.Random` is thread-safe.

But based on Javadoc, contention will cause poor performance.

So you'd better use a thread-local `Random` as follows:

  private static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() {
    @Override
    protected Random initialValue() {
      return new Random();
    }
  };

RANDOM.get().nextInt(100);

If you use JDK 1.7 or greater,

you can use `java.util.concurrent.ThreadLocalRandom` as follows:

ThreadLocalRandom.current().nextInt(100);

No comments:

Post a Comment