File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Better way of random number generation using multiple threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Better way of random number generation using multiple threads" Watch "Better way of random number generation using multiple threads" New topic
Author

Better way of random number generation using multiple threads

naresh babu
Greenhorn

Joined: Sep 04, 2007
Posts: 8
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

Joined: Oct 27, 2005
Posts: 19718
    
  20

You can check out java.util.UUID.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42264
    
  64
What's the code to run this in multiple threads?


Ping & DNS - my free Android networking tools app
naresh babu
Greenhorn

Joined: Sep 04, 2007
Posts: 8
Code will be called from the sevlet.
David Balažic
Ranch Hand

Joined: May 15, 2008
Posts: 86
Multiple threads call getRandomString() at the same time ?

Try adding the thread id for seed:
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
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

Joined: Mar 05, 2008
Posts: 3018
    
  10
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

Joined: Aug 11, 2007
Posts: 4659
    
    5

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

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
[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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Better way of random number generation using multiple threads