HawaiiStateDigitalArchives / PID-webservice

Apache License 2.0
0 stars 1 forks source link

Use Random.longs() to generate random long values #9

Open dagnir opened 8 years ago

dagnir commented 8 years ago

In randomMint(), Random.longs(long,long) can be used to generate random long values in a range uniformly

Khyzad commented 8 years ago

I don't seem to have that method available in my java platform (1.7). I thought it was using 1.8 as it even says in my POM but it doesn't seem I can change it.

dagnir commented 8 years ago

Do you have JDK 8 installed? It works fine on my machine (just adding a random Rng.longs() call in IdGenerator)

Khyzad commented 8 years ago

Apparently I didn't. Which was interesting because I definitely thought I did. Oh well.

Is there a reason why we're using Random.longs()? I took a look at the methods and they claim that the nextLong(), a method that longs() depends on, uses a seed value that only uses 48 bits (instead of what I assume would be the preferred 64 bits. I'm not sure what percentage of long values this covers), making it impossible to generate all possible long values. This would mean that there would be a region of possible long values that could not be reached without incrementation, thereby only making the region sequentially accessible.

dagnir commented 8 years ago

The reason to prefer longs() is to let Random take care of removing possible bias that can be introduced when using % to make the numbers fall in a given range (see http://stackoverflow.com/q/10984974). The 48-bit seed limitation only applies to Random, not SecureRandom; there shouldn't be any problems generating the entire 64-bit range with SecureRandom. Note longs() is implemented by Random, but uses next() which is overriden by SecureRandom to generate the bytes.