Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java threaded Random.nextLong() returning the same number

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();
    }
}

}

like image 488
Grantland Chew Avatar asked Feb 25 '23 07:02

Grantland Chew


1 Answers

You might not want to be creating a new instance of Random each time. Rather have a global one.

like image 128
sblundy Avatar answered Mar 06 '23 19:03

sblundy