Java generate random numbers Random, ThreadLocalRandom, SecureRandom, Ma

We say it is common Java generate random numbers in several ways: Random, ThreadLocalRandom, SecureRandom; in fact, generate random numbers, but there are many ways our common on these types, if you need to learn more about the three class, you can view JAVA API.

= New new Random Random Random ();
int random.nextInt A = (. 5); // 0 to 4 randomly generated digital intermediate
fact Random constructor is, he can pass the value of a parameter of long type, when empty the construction time, the use is actually System.nanoTime () is the value of the current time in milliseconds, we call this seed.

Seeds are doing it, we generate random numbers are actually pseudo-random number, but we want to make the random number generated higher strength, we need better algorithms and seeds. In general, to use the Random to generate a random number, empty constructor directly on it. Then the seeds in the end what use is it, in fact, to test the reader to know that we use a fixed random number, such as 1, and then we go to new times this Random, then go to generate a random number, like this, you will We found that the result is the same number three.

/**
 * -1157793070
 * 1913984760
 * 1107254586
 */
@Test
public void test2(){
    Random random = new Random(10); 
    for (int i = 0; i < 3; i++){
        System.out.println(random.nextInt());
    }
}

Therefore, we must not put the seed-coded, with the number of milliseconds the current time, it is quite better. In addition, the use of Random try not to repeat new objects, it is not too significant. Concluded that, Random thread-safe, go here you can see the official documents, "Instances of java.util.Random are threadsafe.". But in multi-threaded performance, and his performance is poor.

In the Java API Help documentation, summed up the description of the Random:

java.util.Random random algorithm implemented in the class is a pseudo-random, random rules is the so-called regular number is randomly generated within a range given species (SEED) of;
the Random number of objects of the same seed, the same number the generated random numbers are identical;

The method of generating a random number for each class Random are uniformly distributed, the probability number that is generated inside the equalization section;

This class is Java7 new class, multi-threaded to generate random numbers used. Why ThreadLocalRandom it faster than Random, Random This is because the use of CAS (compare and set) when generating random numbers, but ThreadLocalRandom did not use.

The following is a method of generating random numbers java.util.Random of:

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));
}
而这边的seed是一个全局变量:

/**

  • The internal state associated with this pseudorandom number generator.
  • (The specs for the methods in this class describe the ongoing
  • the this value of Computation).
    * /
    Private Final AtomicLong the SEED;
    multiple threads at the same time get a random number, will be competing for the same seed, resulted in reduced efficiency.

Visible, which guarantee thread safety by way of CAS. This highly concurrent environments due to competition between threads will inevitably bring some performance loss.

At this point comes in handy ThreadLocal, ThreadLocal ThreadLocalRandom through improved tools for random number generation, each individual thread holds a ThreadLocalRandom object reference, which completely eliminated the competition between threads.

Further examples of comparison ThreadLocalRandom particular, the following simple example look.

ThreadLocalRandom = ThreadLocalRandom.current ThreadLocalRandom ();
int A = threadLocalRandom.nextInt (5);
because it is binding and thread, so he also acquired from the current thread.

When you need to generate random numbers frequently, or high security requirements, do not use Random, this is well understood right from the beginning we introduce can know, Random generated value is actually predictable.

Two kinds of built-in random number algorithm, NativePRNG and SHA1PRNG, see the examples of the method. Initialized by the new, by default it will use NativePRNG algorithm to generate random numbers, but can also be configured to modify the algorithm parameters -Djava.security call. If it is / dev / [u] random one of the two is NativePRNG, otherwise SHA1PRNG.

In addition jvm startup parameters such like, -Djava.security = file: / dev / urandom.

Of course, you can also be initialized by getInstance object has one parameter, the name of an algorithm is directly transmitted on the line, if there is no algorithm Throws; two additional parameters, the second parameter may also specify the algorithm package. Let's look at the implementation code.

SecureRandom = new new SecureRandom SecureRandom ();
SecureRandom secureRandom3 = SecureRandom.getInstance ( "SHA1PRNG");
SecureRandom secureRandom2 = SecureRandom.getInstance ( "SHA1PRNG", "SUN");
of course, when we use this class to generate a random number, as only need to generate a random number is generated each time an instance like, did not need to be regenerated every time an object. In addition, this class generates a random number, the first call to the relatively poor performance, first call about nextInt if conditions allow the best service to start ().

In addition, the performance is actually better than NativePRNG SHA1PRNG nearly double the performance is good, less than half the synchronized code, so there is no special emphasis on safety

The whole need to make use of SHA1PRNG algorithm to generate random numbers.

This is a commonly used way of generating a random number, generated by default decimal between 0 and 1.

to sum up:

1, if the stand-alone case where less demanding safety, use the Random; high security requirements, to use a SecureRandom;

SecureRandom There are two algorithms, SHA1PRNG and NativePRNG, SHA1PRNG good performance, but NativePRNG of safety.

2, Random thread-safe, with CAS to maintain, but not higher than the performance, so multiple threads to make use of java concurrency bag ThreadLocalRandom,

To avoid performance problems caused by competition between threads

Guess you like

Origin blog.51cto.com/14477123/2471814