There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has there own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a psuedorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0. Internally it uses java.util.Random class. So when you first call this method, it creates instance of Random class and cache it for future use. Any further call is just equivalent of Random.nextDouble(). If your requirement is more sophisticated i.e. you need random numbers between a range or multiple threads needs to generate random number simultaneously, then you should look other random solution available in Java. Since Math.random() method is properly synchronized to ensure correct value is returned when used by multiple thread, it also become bottleneck when multiple thread simultaneously uses it. To solve this problem, JDK 1.7 introduces ThreadLocalRandom class, which allows each thread to keep their own psuedo random number to reduce contention. In a scalable environment, ThreadLocalRandom can improve performance significantly as it keeps the instance of random number generator in a ThreadLocal variable to reduce contention. If security is your concern then you have another option in terms of SecureRandom, which provides a cryptographically strong random number generator. If you are interested to learn more about ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks, he has covered them in good detail in a separate section.
Read more »
No comments:
Post a Comment