multithreading - Java threaded Random.nextLong() returning the same number -
i'm using oauth library calls new random().nextlong() generate nonces, generates same nonce on asynchronous calls. i've narrowed down threading random.nextlong() returning same exact number every often.
does know if known limitation of java? if so, know of thread safe operation?
edit: i'm using java 1.6
edit: small program made test out going on in larger app. ran several times , more should, coming same random number when time same. please excuse 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 creating new instance of random each time. rather have global one.
Comments
Post a Comment