Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Better way of random number generation using multiple threads

 
naresh babu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am using the following code to generate the random number. This code still gives the same number for multiple threads. I need better way of generating a random number with no ambiguity with multiple threads.
======================================================================
private String generateRandomDocName() {
int nDigits = 9;
String rNumber = "";
rNumber = getRandomString ("1234567890ABCDEF", nDigits);
}
private String getRandomString (String charset, int length) {
Random rnd = new Random (System.currentTimeMillis());
StringBuffer sb = new StringBuffer(length);
int nChars = charset.length();
int rndIdx;
for (int i = 0; i < length; i++)
{
rndIdx = rnd.nextInt(nChars);
sb.append(charset.substring(rndIdx, rndIdx + 1));
}
return sb.toString();
}
===============================================================
Any inputs on this will help me.

Thanks and Regards,
Naresh
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can check out java.util.UUID.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the code to run this in multiple threads?
 
naresh babu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code will be called from the sevlet.
 
David BalaĹžic
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Multiple threads call getRandomString() at the same time ?

Try adding the thread id for seed:
 
Mike Simmons
Ranch Hand
Posts: 3076
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also simply make rnd a static final variable. Though it's not really documented, Random is designed to be used safely by multiple concurrent threads, ensuring that each gets a different random number.
 
Mike Simmons
Ranch Hand
Posts: 3076
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually using thread id that way seems risky. You could easily have two threads with similar ids calling this method at similar times, that get the same seed. You could probably avoid this by including a large multiplier for the id:

Yes, this will overflow and truncate, but I don't see that as a problem. The point is, you'll get unique seeds for each thread.

It's a bit wasteful to create a new Random for every method call, anyway. In the event that the single static Random is a performance bottleneck, I'd use a static ThreadLocal to create one Random per thread, initialized as above.
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mike Simmons:
It's a bit wasteful to create a new Random for every method call, anyway. In the event that the single static Random is a performance bottleneck, I'd use a static ThreadLocal to create one Random per thread, initialized as above.


Its a bit wasteful to create a new Random for each thread. They can all share a common one. Its not a big deal when you use Random, but when you use SecureRandom, there is significant startup overhead.
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, as of Java 5+ you will get a more random number (with multiple Random instances) by using:
Random rnd = new Random();
instead of
Random rnd = new Random(System.currentTimeMillis());

The new implementation of Random uses System.nanoTime() plus a static incrementing seed to initialize the random number, which will give a lot more granularity than currentTimeMillis(). From the API "This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor" whereas when you provide the seed you are setting "the initial value of the internal state of the pseudorandom number generator" and so will get the same sequence of numbers if you provide the same seed (which you can if the threads are run in quick succession).

So you are better off:
1) Using a single Random object that all threads share
2) Using the Random(void) constructor rather than providing your own seed.
 
Mike Simmons
Ranch Hand
Posts: 3076
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Pat]: Its a bit wasteful to create a new Random for each thread. They can all share a common one. Its not a big deal when you use Random, but when you use SecureRandom, there is significant startup overhead.

For most situations, I agree. I did say, if accessing the single static is a performance bottleneck. It probably isn't. But it's possible it might be, and there are some scenarios in which the ThreadLocal solution may give better performance. Of course it's also more complicated, so by all means, using a single static Random should be the first choice. That's why I suggested it.

[Steve]: Also, as of Java 5+ you will get a more random number (with multiple Random instances) by using:

Ah yes, I'd forgotten that they added the uniquifier in 5. Thanks.
[ September 13, 2008: Message edited by: Mike Simmons ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic