The source code is for testing only and should not be used commercially. The source code comes from the Internet. If there is any infringement, please contact me to remove it.
java随机数的陷阱

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.RandomCome 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.RandomA 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.RandomThe usage of is thread-safe. However, using the sameRandomInstances 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 atRandomofnext(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.ThreadLocalRandomexpandedRandomAnd add options to restrict its use to the corresponding thread instance. To this end,ThreadLocalRandomAn 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

throughRandomSome analysis of the analysis we can knowRandomIn 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, useRandomIt is not suitable, and it is easy for others to take advantage of it. JDK providesSecureRandomto solve this matter.
SecureRandomIs 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.

read more
Resource download
PriceFree
The use is limited to testing, experiments, and research purposes. It is prohibited for all commercial operations. This team is not responsible for any illegal behavior of users during use. Please self-test all source codes! There is no guarantee of the integrity and validity of your source code. All source code is collected from the entire network
Original link:https://bcbccb.cn/en/3156.html, please indicate the source for reprinting. Disclaimer: This resource has not been authorized by the original rights holder and is not commercially available. It can only be used to learn and analyze the underlying code, CSS, etc., and is prohibited for commercial purposes. Any relevant disputes and legal liabilities arising from unauthorized commercial use shall be fully borne by the user. Everyone is responsible to support genuine copies. Please delete them within 24 hours after downloading. Thank you for your support!
1

Comments0

经典海外游戏源码海外高端娱乐游戏源码全开源 带教程
Classic overseas game source code overseas high-end entertainment game source code fully open source with tutorial
Someone bought it 6 minutes ago Go and have a look

Site Announcements

The source code (theme/plug-in/application source code) and other resources provided by this site are only for learning and exchange

Commercial use is prohibited, otherwise all consequences will be borne by the downloading user!

Some resources are collected or copied online. If they infringe on your legitimate rights and interests, please write to us.

Currently, members have a big reward, and the current price for a lifetime member is 299 gold coins.Recent price adjustments

Join quickly, opportunities wait for no one! immediately participated in

Captcha

Fast login to social accounts

en_USEnglish