
preface
We should be familiar with random numbers. In business, we use them to generate Captcha, or IDs that require less duplication, and we even use them to hold raffle at the annual meeting. Today we will discuss this thing. If used incorrectly, it can cause a series of problems.
Random numbers in java
We need to generate a number randomly in Java. We usually use Java developmentjava.util.Random
Come and do, it provides a pseudo-random generation mechanism. Jvm determines the interval for generating random numbers through the passed seeds. As long as the seeds are the same, the sequence of obtained random numbers is consistent. And the results generated are predictable. It is an implementation of a pseudo-random number rather than a true random number. To determine the use, but some use cases directly may cause some unexpected problems.Random
A common usage of:
// Random example
Random random = new Random();
//Call the nextInt() method In addition to nextDouble(), nextBoolean(), nextFloat(),...
random.nextInt();
Alternatively, we can use mathematical calculation classes in java:
Math.random();
The Math class contains only one Random instance to generate random numbers:
public static double random() {
Random rnd = randomNumberGenerator;
if (rnd == null) {
// 返回一个新的Random实例
rnd = initRNG();
}
return rnd.nextDouble();
}
java.util.Random
The usage of is thread-safe. However, using the sameRandom
Instances can cause contention, resulting in poor performance. The reason for this is the use of so-called seeds to generate random numbers. A seed is a simple number that provides the basis for generating new random numbers. 's take a look atRandom
ofnext(int bits)
Method:
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 new seeds, usecompareAndSet()
Method replaces the old seed with the next new seed, but this will only trigger if the old seed corresponds to the currently set seed. If the value at this time is manipulated by a concurrent thread, the method returnsfalse
, which means that the old value does not match the exception value. Because it is an operation within a loop, spinning occurs until the variable matches the exception value. This can lead to poor performance and thread competition.
Random numbers under multithreading
If more threads actively generate new random numbers with instances of the same Random, the higher the probability of this happening. This method is not recommended for programs that generate many (very many) random numbers. In this case, you should useThreadLocalRandom
, it was added to Java in version 1.7.ThreadLocalRandom
expandedRandom
And add options to restrict its use to the corresponding thread instance. To this end,ThreadLocalRandom
An instance of is saved in the internal map of the corresponding thread and is saved by callingcurrent()
to return the correspondingRandom
。Use as follows:
ThreadLocalRandom.current().nextInt()
Safe random number
throughRandom
Some analysis of the analysis we can knowRandom
In fact, it is pseudo-random, rules can be deduced and depends on the seed. If we have a lottery or some other random number-sensitive scene, useRandom
It is not suitable, and it is easy for others to take advantage of it. JDK providesSecureRandom
to solve this matter.
SecureRandom
Is a strong random number generator that can generate high-intensity random numbers. Generating high-intensity random numbers relies on two important factors: seeds and algorithm. There can be many algorithms, and how to select seeds is usually a very critical factor. Random's seed isSystem.currentTimeMillis()
, so its random numbers are all predictable and weak pseudo-random numbers. The idea of generating strong pseudo-random numbers: Collect various information about the 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 an approximately random seed, mainly to achieve unpredictability. To put it more generally, using an encryption algorithm to generate a long random seed makes it impossible for you to guess the seed and deduce the number of random sequences.
summary
Today we discussed some mechanisms of random numbers often used in business and some traps in some scenarios. We hope you can avoid this trap when using random numbers.
Comments0