Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Java random numbers and the usage of random numbers under multithreading

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly talks about "Java random numbers and the use of random numbers under multithreading". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn "Java random numbers and the use of random numbers under multithreading"!

Random numbers in Java

We need to randomly generate a number in Java. We usually use java.util.Random in java development, which provides a pseudo-random generation mechanism. Jvm determines the interval of generating random numbers by passing in the seed (seed). As long as the seeds are the same, the sequence of random numbers obtained is consistent. And the results are predictable. It is an implementation of pseudo-random number, not a real random number. To determine what is used, but the direct use of some use cases can lead to unexpected problems. A common use of Random:

/ / Random instance Random random = new Random (); / / call the nextInt () method in addition to nextDouble (), nextBoolean (), nextFloat (),... Random.nextInt ()

Alternatively, we can use the mathematical calculation class in java:

Math.random ()

The Math class contains only one instance of Random to generate random numbers:

Public static double random () {Random rnd = randomNumberGenerator; if (rnd = = null) {/ / returns a new Random instance rnd = initRNG ();} return rnd.nextDouble ();}

The use of java.util.Random is thread safe. However, concurrently using the same Random instance on different threads can lead to contention, resulting in poor performance. The reason is that so-called seeds are used to generate random numbers. A seed is a simple number that provides the basis for generating new random numbers. Let's look at the next (int bits) method in Random:

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));}

First, the old seed and the new seed are stored on two auxiliary variables. At this point, the principle of creating new seeds is not important. To save the new seed, use the compareAndSet () method to replace the old seed with the next new seed, but this is triggered only if the old seed corresponds to the currently set seed. If the value at this time is manipulated by a concurrent thread, the method returns false, which means that the old value does not match the exception value. Because the operation is done within the loop, spin occurs until the variable matches the exception value. This can lead to poor performance and thread competition.

Random numbers under multithreading

The higher the probability that this will happen, if more threads actively generate new random numbers for instances with the same Random. This approach is not recommended for programs that generate many (very many) random numbers. In this case, you should use ThreadLocalRandom, which was added to Java in version 1.7. ThreadLocalRandom extends Random and adds options to limit its use to the corresponding thread instance. To do this, the instance of ThreadLocalRandom is saved in the internal mapping of the corresponding thread and the corresponding Random is returned by calling current (). The mode of use is as follows:

ThreadLocalRandom.current () .nextInt ()

Safe random number

Through some analysis of Random, we can know that Random is in fact pseudo-random, can deduce the law, and depends on seed. If we have a lucky draw or other scenes that are sensitive to random numbers, Random is not appropriate and is easy to be exploited. JDK provides SecureRandom to solve this problem.

SecureRandom is a strong random number generator, which can generate high-intensity random numbers. The generation of high-intensity random numbers depends on two important factors: seed and algorithm. There can be many algorithms, and usually how to choose the seed is a very critical factor. The seed of Random is System.currentTimeMillis (), so its random numbers are predictable and are weakly pseudorandom. The idea of generating strong pseudorandom number: collect all kinds of information of computer, keyboard input time, memory usage status, hard disk free space, IO delay, number of processes, number of threads and other information, CPU clock, to get a nearly random seed, mainly to achieve unpredictability. It is more common to use encryption algorithms to generate a long random seed, so that you cannot guess the seed and deduce the random sequence number.

At this point, I believe that everyone on the "Java random numbers and multithreaded random number usage" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report