I'm using an OAuth library that calls new Random().nextLong() to generate nonces, however it generates the same nonce on asynchronous calls. I've narrowed it down to threading Random.nextLong() to returning the same exact number every so often.
Does anyone know if this is a known limitation of Java? If so, does anyone know of a thread safe operation?
EDIT: I'm using Java 1.6
EDIT: This is a small program I made to test out what was going on in my larger app. I ran this several times and more often that it should, it was coming up with the same random number when the time was the same. Please excuse my quick programming.
public class ThreadedRandom {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ThreadedRandom().run();
}
private RandomNumberGenerator _generator;
public ThreadedRandom()
{
_generator = new RandomNumberGenerator();
}
public void run()
{
Runnable r = new Runnable() {
@Override public void run() {
System.out.println(System.currentTimeMillis()+"\t"+_generator.gen());
}
};
Thread t1, t2;
t1 = new Thread(r);
t2 = new Thread(r);
t1.start();
t2.start();
}
private class RandomNumberGenerator {
Random random;
public RandomNumberGenerator()
{
random = new Random();
}
public Long gen() {
return new Random().nextLong();
}
}
}
You might not want to be creating a new instance of Random each time. Rather have a global one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With