Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

java - Random over ThreadLocalRandom

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

What kind of contention and thus poor performance ? Can anybody please, explain me here ? I don't know what algorithm goes inside Random and ThreadLocalRandom that makes them different.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This might help a little:

http://thoughtfuljava.blogspot.com/2012/09/prefer-threadlocalrandom-over-random.html


Quoted from source:

Normally to generate random numbers, we either do create an instance of java.util.Random or Math.random() - which internally creates an instance of java.util.Random on first invocation. However, in a concurrent applications usage of above leads to contention issues.

Random is thread safe for use by multiple threads. But if multiple threads use the same instance of Random, the same seed is shared by multiple threads. It leads to contention between multiple threads and so to performance degradation.

ThreadLocalRandom is solution to above problem. ThreadLocalRandom has a Random instance per thread and safeguards against contention.


So, basically, using a random instance per thread allows you to stop synchronizing on the seed which must be used by all threads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...