What is a cross-platform way to select random seed in Java?

After reading this answer: the best way to pick a random subset from a collection?

I am wondering how to select random seed in Java?

And don't say use System.currentTimeMillis () or System.nanoTime (). Read the article to understand why not.

This is a difficult question, but let me make it harder. Let's say you need to create a random seed without connecting to the Internet, without using user input (IE, there is no gui there), and it should be cross-platform (so there is no JNI to access the equipment).

Are there some JVM variables that we can control as a source of our randomness?

Can this be done? Or is it impossible?

+4
source share
3 answers

Take a look at Fancy Maths (full disclosure: I wrote this). It should solve most of the problems you have ever had with random numbers in Java.

Even if you do not use it, you can get some ideas from the various SeedGenerator that it provides. Basically, the default is / dev / random . If this does not exist (for example, Windows), it either tries to download data from random.org , or uses SecureRandom.generateSeed .

I think SecureRandom.generateSeed is the best you can do without relying on any platform or the Internet.

+6
source

Combine System.currentTimeMillis() with a global counter, which you increment each time you create a seed. Use AtomicLong for a counter so you can increase the efficiency and safety of threads.

“Combination” does not mean “add” or “xor” because it is too easy to get duplicates. Instead, a hash. You can get complicated and fill in a long and counter, for example. 16 bytes and MD5, but I would probably use the 64-bit version of the CRC Adler or another 64-bit CRC .

0
source

Um, this article says 32-bit seeds are bad, but 64-bit seeds are good. System.currentTimeMillis () is a 64-bit seed.

0
source

Source: https://habr.com/ru/post/1277191/


All Articles